今天準備opentalk資料的時候,無意間發現一段很有意思的代碼,特此記錄一下:
/**
* @author dxc
* @date 2018/11/4
*/
public class StringInternTest {
public static void main(String[] args) {
String s = new String("1");
s.intern();
String s2 = "1";
System.out.println(s == s2);
String s3 = new String("1") + new String("1");
//String s3 = "1" + "1";
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);
System.out.println(s3.equals(s4));
}
}
上述代碼在JDK8(“1.8.0_172”)的環境下運行結果是:
false
true
true
在JDK9(“9.0.1”)的環境下運行結果是:
false
false
true
感覺很奇怪,JDK9按道理不應該和JDK8的結果一致麼?難道JDK9和JDK8兩個版本的String.intern()實現機制不同?我確定我的java版本沒有搞錯呢。暫時記錄一下這個問題,考慮到JDK9不是長期維護版本,JDK11已經發布,後面要看一下在JDK11的環境下這段代碼是什麼結果。
stackoverflow提問地址:https://stackoverflow.com/questions/53141338/why-does-string-intern-return-different-results-under-jdk8-and-jdk9
所使用的兩個java version :
JDK8:
JDK9:
看了stackoverflow上的回答,應該是JDK9中的"11"已經存在常量池中了,而JDK8中"11"不在常量池中導致的。把"11"換成其他胡亂的字符串,程序運行結果是和JDK8一致的(false-true-true);如果把"11"換成常量池中已有的"java"字符串,則返回結果和"11"一致,驗證了這種結論。
以下代碼,JDK8和JDK9都返回:
false
false
true
代碼:
/**
* @author dxc
* @date 2018/11/4 0004
*/
public class StringInternTest {
public static void main(String[] args) {
String s = new String("1");
s.intern();
String s2 = "1";
System.out.println(s == s2);
String s3 = new String("ja") + new String("va");
//String s3 = "1" + "1";
s3.intern();
String s4 = "java";
System.out.println(s3 == s4);
System.out.println(s3.equals(s4));
}
}
PS:JDK 9 和 JDK 10 都不是長期維護版本,長期維護的JDK 11版本 已經發布,9和10已經成爲歷史了。。。自己玩的話,還是早點換成最新的JDK11吧。