先看下代码及反编译后的代码:
/**
* @author doctor
*
* @time 2015年3月28日 下午3:26:06
*/
public class StringForSwitch {
@Rule
public ExpectedException ex = ExpectedException.none();
@Test
public void test_string_switch() {
String result="";
switch ("doctor") {
case "doctor":
result = "doctor";
break;
default:
break;
}
assertThat(result, equalTo("doctor"));
}
}
反编译后的代码:
public class StringForSwitch {
@Rule
public ExpectedException ex = ExpectedException.none();
public StringForSwitch() {
}
@Test
public void test_string_switch() {
String result = "";
String var2 = "doctor";
switch("doctor".hashCode()) {
case -1326477025:
if(var2.equals("doctor")) {
result = "doctor";
}
default:
Assert.assertThat(result, IsEqual.equalTo("doctor"));
}
}
}
1.字符串类型在switch语句中利用hashcode的值与字符串内容的比较来实现的.
2.因为字符串的哈希值可能重复,哈希函数设计的不好吧.故还得需要进一步比较字符串的内容.
3.编译器层面的语法糖而已,实质没变,switch还是比较的整数.
4.jdk1.8.0_40环境下.