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

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

    The following is a complete example based on JeeBee's post, using java enum's instead of using a custom method.

    Note that in Java SE 7 and later you can use a String object in the switch statement's expression instead.

    public class Main {
    
        /**
        * @param args the command line arguments
        */
        public static void main(String[] args) {
    
          String current = args[0];
          Days currentDay = Days.valueOf(current.toUpperCase());
    
          switch (currentDay) {
              case MONDAY:
              case TUESDAY:
              case WEDNESDAY:
                  System.out.println("boring");
                  break;
              case THURSDAY:
                  System.out.println("getting better");
              case FRIDAY:
              case SATURDAY:
              case SUNDAY:
                  System.out.println("much better");
                  break;
    
          }
      }
    
      public enum Days {
    
        MONDAY,
        TUESDAY,
        WEDNESDAY,
        THURSDAY,
        FRIDAY,
        SATURDAY,
        SUNDAY
      }
    }
    
    0 讨论(0)
  • 2020-11-21 08:20

    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.

    The designers of C# decided that the style was important, even if there was no advantage.

    The designers of Java apparently thought like the designers of C.

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

    For years we've been using a(n open source) preprocessor for this.

    //#switch(target)
    case "foo": code;
    //#end
    

    Preprocessed files are named Foo.jpp and get processed into Foo.java with an ant script.

    Advantage is it is processed into Java that runs on 1.0 (although typically we only supported back to 1.4). Also it was far easier to do this (lots of string switches) compared to fudging it with enums or other workarounds - code was a lot easier to read, maintain, and understand. IIRC (can't provide statistics or technical reasoning at this point) it was also faster than the natural Java equivalents.

    Disadvantages are you aren't editing Java so it's a bit more workflow (edit, process, compile/test) plus an IDE will link back to the Java which is a little convoluted (the switch becomes a series of if/else logic steps) and the switch case order is not maintained.

    I wouldn't recommend it for 1.7+ but it's useful if you want to program Java that targets earlier JVMs (since Joe public rarely has the latest installed).

    You can get it from SVN or browse the code online. You'll need EBuild to build it as-is.

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

    If you have a place in your code where you can switch on a String, then it may be better to refactor the String to be an enumeration of the possible values, which you can switch on. Of course, you limit the potential values of Strings you can have to those in the enumeration, which may or may not be desired.

    Of course your enumeration could have an entry for 'other', and a fromString(String) method, then you could have

    ValueEnum enumval = ValueEnum.fromString(myString);
    switch (enumval) {
       case MILK: lap(); break;
       case WATER: sip(); break;
       case BEER: quaff(); break;
       case OTHER: 
       default: dance(); break;
    }
    
    0 讨论(0)
提交回复
热议问题