Switch语句的参数类型
-
JDK1.6 的版本中,switch后面的括号里面只能放int类型的值,
注意是只能放int类型,但是放byte,short,char类型的也可以。是因为byte,short,shar可以自动提升(自动类型转换)为int。而不能放long型和String型。
JDK1.7 的版本中,switch中可以使用字串String。但仍不支持long型。
-
原理: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;
}
}
}