Why can't I use switch statement on a String?

前端 未结 16 2025
面向向阳花
面向向阳花 2020-11-21 07:57

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

16条回答
  •  既然无缘
    2020-11-21 08:03

    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;
                }
            }
        }
    }
    

提交回复
热议问题