引言
switch对字符串的支持是从JDK7开始的
实现原理
switch对字符串的处理和基本数据类型的处理有一点点的不一样,
它会字符串转为HashCode码来转到对应的分支,分支中的字符串也会转成HashCode码,HashCode码为int类型,switch这样处理字符串就和int类型的一致,只是在内部再一次使用equals对原字符串进行比较
代码示例
public class SwitchStringDemo {
public static void main(String[] args) {
// String
String str = "two";
switch (str) {
case "one":
System.out.println("one");
break;
case "two":
System.out.println("two");
break;
default:
System.out.println("其他...");
break;
}
// int
int num = 1;
switch (num) {
case 1:
System.out.println("1111111");
break;
case 2:
System.out.println("2222222");
break;
default:
System.out.println("其他...");
break;
}
}
}
反编译代码
public class SwitchStringDemo {
public static void main(String[] args) {
// String类型的switch
label25 : {
String str = "two";
switch (str.hashCode()) { // 此处使用字符串的HashCode码
case 110182 : // 字符串转为HashCode码
if (str.equals("one")) { // 再一次使用equals比较
System.out.println("one");
break label25;
}
break;
case 115276 : // 字符串转为HashCode码
if (str.equals("two")) {
System.out.println("two");
break label25;
}
}
System.out.println("其他...");
}
// int类型的switch
int num = 1;
switch (num) {
case 1 :
System.out.println("1111111");
break;
case 2 :
System.out.println("2222222");
break;
default :
System.out.println("其他...");
}
}
}