首页 > 其他分享 >intern

intern

时间:2024-05-10 14:49:08浏览次数:16  
标签:String s2 s1 intern 123 new

 9     static void test01(){
10         String s1 = new String("1")+new String("23");
11         s1.intern();
12         String s2 = "123";
13         System.out.println( s1 == s2);//true
14     }
15 
16     static void test02(){
17         String s1 = new String("1")+new String("23");
18         String s2 = "123";
19         s1.intern();
20         System.out.println( s1 == s2); //false
21     }

  s1.intern 在常量池植入引用,指向堆里面的"123",s2来的时候先看常量区,已经有了(虽然只是一个引用),直接给变量赋值

23     static void test03(){
24         String s1 = new String("1")+new String("23");
25         String s2 = "123";
26         System.out.println( s1 == s2);//false
27         s1.intern();
28         System.out.println( s1 == s2);//false
29         s1 = s1.intern();
30         System.out.println( s1 == s2);//true
31     }

  s1.intern试图在常量池植入"123",一看已经有了,返回常量池 “123”的引用,什么都不干,27行返回值没用所以28行还是false,29行用了给s1赋值,然后s1和s2就指向同一片了

标签:String,s2,s1,intern,123,new
From: https://www.cnblogs.com/silyvin/p/18184271

相关文章