在JDK1.7
之后,switch提供了对String字符串的支持,而在我们印象之中,Switch只提供byte,char,short,int类型的常量表达式的支持,为什么JDK7
之中能对String字符串对象使用呢?抱着这个疑问,就有了本文。
首先,让我们看一下一般情况下Switch语句写法:
int num = 1;
switch (num) {
case 2:
System.out.println(2);
break;
case 1:
System.out.println(1);
break;
default:
break;
}
反编译后:
int a = 5;
switch(a) {
case 2:
System.out.println(2);
break;
case 1:
System.out.println(1);
break;
}
再看看String字符串下的:
String str = "lby";
switch (str) {
case "dcy":
System.out.println("dcy");
break;
case "lby":
System.out.println("lby");
break;
default:
break;
}
反编译后:
String str = "lby";
String s;
switch((s = str).hashCode()) {
default:
break;
case 99290:
if(s.equals("dcy"))
System.out.println("dcy");
break;
case 106947:
if(s.equals("lby"))
System.out.println("lby");
break;
}
经过上面我们可以发现,Switch对String类型支持是经过hashCode
转换成int类型再进行判断的,并且,为了防止发生Hash值相同情况,还采用了equals
方法对字符串进行比较。
其实可以试验一下其他类型,本质都是转换成int类型进行比较,而对于超过int范围,如long类型,switch则不提供支持。