前提:jdk版本为1.8.0_73
java代码:
public class test {
public static void main(String[] args) throws Exception {
String str = "a" + "b";
for (int i = 0; i < 10; i++) {
str = str.concat(i + "");
}
System.out.println(str);
String a = "aszx";
switch (a) {
case "as":
System.out.println(a);
break;
case "aszx":
System.out.println(a);
break;
default:
System.out.println("default:" + a);
}
}
}
字节码文件:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
public class test {
public test() {
}
public static void main(String[] var0) throws Exception {
String var1 = "ab";
for(int var2 = 0; var2 < 10; ++var2) {
var1 = var1.concat(var2 + "");
}
System.out.println(var1);
String var5 = "aszx";
byte var4 = -1;
switch(var5.hashCode()) {
case 3122:
if (var5.equals("as")) {
var4 = 0;
}
break;
case 3004144:
if (var5.equals("aszx")) {
var4 = 1;
}
break;
}
switch(var4) {
case 0:
System.out.println(var5);
break;
case 1:
System.out.println(var5);
break;
default:
System.out.println("default:" + var5);
}
}
}
可以看出:
1.对于String类型变量,在定义时,用"+"连接,编译后会优化成一个常量
2.switch对String的支持,是通过String变量的hashCode码+equals()方法(由于hash冲突的存在,equals()方法不可省略),将String变量映射到一个数字型变量(byte、short、int等,经实测,该变量类型与case分支数量有关),再使用switch选择
本文探讨了Java中字符串连接的编译优化过程及switch语句如何处理字符串输入,展示了具体的字节码文件对比,解释了hashCode和equals方法在switch-case结构中的作用。
2019

被折叠的 条评论
为什么被折叠?



