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

前端 未结 16 2015
面向向阳花
面向向阳花 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:02

    Not very pretty, but here is another way for Java 6 and bellow:

    String runFct = 
            queryType.equals("eq") ? "method1":
            queryType.equals("L_L")? "method2":
            queryType.equals("L_R")? "method3":
            queryType.equals("L_LR")? "method4":
                "method5";
    Method m = this.getClass().getMethod(runFct);
    m.invoke(this);
    
    0 讨论(0)
  • 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 = "<Your String>";
    
    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<T> {
        private final HashMap<T, Runnable> cases = new HashMap<T, Runnable>(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;
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 08:06

    Switch statements with String cases have been implemented in Java SE 7, at least 16 years after they were first requested. A clear reason for the delay was not provided, but it likely had to do with performance.

    Implementation in JDK 7

    The feature has now been implemented in javac with a "de-sugaring" process; a clean, high-level syntax using String constants in case declarations is expanded at compile-time into more complex code following a pattern. The resulting code uses JVM instructions that have always existed.

    A switch with String cases is translated into two switches during compilation. The first maps each string to a unique integer—its position in the original switch. This is done by first switching on the hash code of the label. The corresponding case is an if statement that tests string equality; if there are collisions on the hash, the test is a cascading if-else-if. The second switch mirrors that in the original source code, but substitutes the case labels with their corresponding positions. This two-step process makes it easy to preserve the flow control of the original switch.

    Switches in the JVM

    For more technical depth on switch, you can refer to the JVM Specification, where the compilation of switch statements is described. In a nutshell, there are two different JVM instructions that can be used for a switch, depending on the sparsity of the constants used by the cases. Both depend on using integer constants for each case to execute efficiently.

    If the constants are dense, they are used as an index (after subtracting the lowest value) into a table of instruction pointers—the tableswitch instruction.

    If the constants are sparse, a binary search for the correct case is performed—the lookupswitch instruction.

    In de-sugaring a switch on String objects, both instructions are likely to be used. The lookupswitch is suitable for the first switch on hash codes to find the original position of the case. The resulting ordinal is a natural fit for a tableswitch.

    Both instructions require the integer constants assigned to each case to be sorted at compile time. At runtime, while the O(1) performance of tableswitch generally appears better than the O(log(n)) performance of lookupswitch, it requires some analysis to determine whether the table is dense enough to justify the space–time tradeoff. Bill Venners wrote a great article that covers this in more detail, along with an under-the-hood look at other Java flow control instructions.

    Before JDK 7

    Prior to JDK 7, enum could approximate a String-based switch. This uses the static valueOf method generated by the compiler on every enum type. For example:

    Pill p = Pill.valueOf(str);
    switch(p) {
      case RED:  pop();  break;
      case BLUE: push(); break;
    }
    
    0 讨论(0)
  • 2020-11-21 08:06

    James Curran succinctly says: "Switches based on integers can be optimized to very efficent code. Switches based on other data type can only be compiled to a series of if() statements. For that reason C & C++ only allow switches on integer types, since it was pointless with other types."

    My opinion, and it's only that, is that as soon as you start switching on non-primitives you need to start thinking about "equals" versus "==". Firstly comparing two strings can be a fairly lengthy procedure, adding to the performance problems that are mentioned above. Secondly if there is switching on strings there will be demand for switching on strings ignoring case, switching on strings considering/ignoring locale,switching on strings based on regex.... I would approve of a decision that saved a lot of time for the language developers at the cost of a small amount of time for programmers.

    0 讨论(0)
  • 2020-11-21 08:07

    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 numerical else 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.

    0 讨论(0)
  • 2020-11-21 08:07

    Other answers have said this was added in Java 7 and given workarounds for earlier versions. This answer tries to answer the "why"

    Java was a reaction to the over-complexities of C++. It was designed to be a simple clean language.

    String got a little bit of special case handling in the language but it seems clear to me that the designers were trying to keep the amount of special casing and syntactic sugar to a minimum.

    switching on strings is fairly complex under the hood since strings are not simple primitive types. It was not a common feature at the time Java was designed and doesn't really fit in well with the minimalist design. Especially as they had decided not to special case == for strings, it would be (and is) a bit strange for case to work where == doesn't.

    Between 1.0 and 1.4 the language itself stayed pretty much the same. Most of the enhancements to Java were on the library side.

    That all changed with Java 5, the language was substantially extended. Further extensions followed in versions 7 and 8. I expect that this change of attitude was driven by the rise of C#

    0 讨论(0)
提交回复
热议问题