Is this functionality going to be put into a later Java version?
Can someone explain why I can't do this, as in, the technical way Java's switch
statement works?
Is this functionality going to be put into a later Java version?
Can someone explain why I can't do this, as in, the technical way Java's switch
statement works?
If you are not using JDK7 or higher, you can use
hashCode()
to simulate it. BecauseString.hashCode()
usually returns different values for different strings and always returns equal values for equal strings, it is fairly reliable (Different strings can produce the same hash code as @Lii mentioned in a comment, such as"FB"
and"Ea"
) See documentation.So, the code would look like this:
That way, you are technically switching on an
int
.Alternatively, you could use the following code:
Beside the above good arguments, I will add that lot of people today see
switch
as an obsolete remainder of procedural past of Java (back to C times).I don't fully share this opinion, I think
switch
can have its usefulness in some cases, at least because of its speed, and anyway it is better than some series of cascading numericalelse if
I saw in some code...But indeed, it is worth looking at the case where you need a switch, and see if it cannot be replaced by something more OO. For example enums in Java 1.5+, perhaps HashTable or some other collection (sometime I regret we don't have (anonymous) functions as first class citizen, as in Lua — which doesn't have switch — or JavaScript) or even polymorphism.