I have noticed that I cannot use long
as expression of the switch() part.
I don't understand why.
This primitive worse than others?
What's wrong with long
?
I have noticed that I cannot use long
as expression of the switch() part.
I don't understand why.
This primitive worse than others?
What's wrong with long
?
It's how switch was built into Java. What you can do, though, is cast long values as int types before you put them into switch.
From the Oracle Documentation:
A
switch
works with thebyte
,short
,char
, andint
primitive data types.
The reason you can't switch on a long
is that there is no need. In order to meaningfully switch on a long
, you would need to add a case
statement for every single value you want to switch to. (The only reason int
s are supported is because that is the default integral type; even for int
s its rather a waste.)
You can use a Map as a sort of switch
Eg instead of:
long choice = getChoice();
if (choice == 1L) {
System.out.println("Do action one");
} else if (choice == 2L) {
System.out.println("Do action two");
} else {
System.out.println("Default action");
}
you can do
Map<Long, Runnable> actionMap = new HashMap<>();
actionMap.put(1L, () -> System.out.println("Do action one"));
actionMap.put(2L, () -> System.out.println("Do action two"));
Runnable defaultAction = () -> System.out.println("Default action");
...
Long choice = getChoice();
Runnable action = actionMap.getOrDefault(choice, defaultAction);
action.run();
The map approach will execute in constant time O(1) whereas the if/then/else will execute in linear time O(N)
As other people have said, you can't use long (or String etc) in a case statement. If you really want to use a long, the obvious choice is to use if/then/else.
eg:
if (someValue == 1L) {
println("one");
} else if (someValue == 2L) {
println("two");
} ...
} else if (someValue == 1000L) {
println("thousand");
}
But if you have many options, this will perform very badly since you need to evaluate each condition. What I was suggesting in my other answer is to use a Map instead
Map<Long, Runnable> map = new HashMap<Long, Runnable>();
map.put(1L, new Runnable() {
public void run() { println("one"); }
});
map.put(2L, new Runnable() { ... });
...
map.put(1000L, new Runnable() { ... });
And then you can use
map.get(someValue).run();
The map version will perform in constant time O(1) whereas the if/then/else will perform in linear time O(N). As you can see, this construct can be used with Long, String or any object you like.
When you use a programming language, you are restricted to that language's definition. In this case, the Java switch
statement
works with the byte, short, char, and int primitive data types
according to the Java language specification.