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
state
If you are not using JDK7 or higher, you can use hashCode()
to simulate it. Because String.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:
String s = "";
switch(s.hashCode()) {
case "Hello".hashCode(): break;
case "Goodbye".hashCode(): break;
}
That way, you are technically switching on an int
.
Alternatively, you could use the following code:
public final class Switch {
private final HashMap cases = new HashMap(0);
public void addCase(T object, Runnable action) {
this.cases.put(object, action);
}
public void SWITCH(T object) {
for (T t : this.cases.keySet()) {
if (object.equals(t)) { // This means that the class works with any object!
this.cases.get(t).run();
break;
}
}
}
}