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

前端 未结 16 2049
面向向阳花
面向向阳花 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: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;
    }
    

提交回复
热议问题