在Java5以前,switch(expr)中,exper只能是byte,short,char,int类型或者其对应的封装类。
从Java5开始,java中引入了枚举类型,即enum类型。
从Java7开始,exper还可以是String类型。其实,jdk1.7并没有新的指令来处理switch string,而是通过调用switch中string.hashCode,将string转换为int从而进行判断。原理:hashCode()+equals()
编译器在编译期间给代码做了转换。
原始代码:
public class StringInSwitchCase {
public static void main(String[] args) {
String mode = args[0];
switch (mode) {
case "ACTIVE":
System.out.println("Application is running on Active mode");
break;
case "PASSIVE":
System.out.println("Application is running on Passive mode");
break;
case "SAFE":
System.out.println("Application is running on Safe mode");
}
}
}
编译器优化后:
import java.io.PrintStream;
public class StringInSwitchCase{
public StringInSwitchCase() { }
public static void main(string args[]) {
String mode = args[0];
String s; switch ((s = mode).hashCode()) {
default: break;
case -74056953:
if (s.equals("PASSIVE")) {
System.out.println("Application is running on Passive mode");
}
break;
case 2537357:
if (s.equals("SAFE")) {
System.out.println("Application is running on Safe mode");
}
break;
case 1925346054:
if (s.equals("ACTIVE")) {
System.out.println("Application is running on Active mode");
}
break;
}
}
}
但是long在所有版本中都是不可以的。
如在jdk 7 之前的版本使用, 会提示如下错误:
Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted
意为jdk版本太低,不支持。