Java7之前无法使用字符串,在Java7以及以后的版本中可以使用字符串
当我们把编译器版本改为1.7的时候:
Switch通过编译,且可以运行
我们将class文件反编译后
String a = "a";
byte var3 = -1;
switch(a.hashCode()) {
case 97:
if(a.equals("a")) {
var3 = 0;
}
break;
case 98:
if(a.equals("b")) {
var3 = 1;
}
}
switch(var3) {
case 0:
System.out.println("a");
break;
case 1:
System.out.println("b");
break;
default:
System.out.println("c");
}
其实这段代码并不难理解,Switch实现对String的操作,主要是对他做了一次hashCode(),而且hashCode()正好返回的是int。