public class Intern {
public static void main(String[] args) {
test1();
test2();
}
public static void test1(){
String s = new String("1");
s.intern();
String s2 = "1";
System.out.println(s == s2);
String s3 = new String("1") + new String("1");
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);
}
public static void test2(){
String s = new String("1");
String s2 = "1";
s.intern();
System.out.println(s == s2);
String s3 = new String("1") + new String("1");
String s4 = "11";
s3.intern();
System.out.println(s3 == s4);
}
}
白話文:test1,new String("1") 的時候吧“1”和new String("1") 放入堆中,這時候運行intern(),會把‘1’放入常量池中
然後s2取到的是常量池中的‘1’,這樣因爲兩個指向的不同,所以爲false
同理,s3創建的時候是把4個東西放入了堆中,new String("1"),new String("11"),new String("1"),“1”,運行方法的時候
發現常量池中沒有“11”,那麼會去堆中的new String("11"),這樣其實兩個的指向是相同的,所以爲true
參考鏈接:https://tech.meituan.com/2014/03/06/in-depth-understanding-string-intern.html(美團技術團隊)