Why are the results of of str == str.intern() for these strings different?

后端 未结 4 2058
说谎
说谎 2020-12-09 17:59
public static void main(String[] args) {
    String str1 = new StringBuilder(\"计算机\").append(\"软件\").toString();
    System.out.println(str1.intern() == str1);
    S         


        
4条回答
  •  渐次进展
    2020-12-09 18:15

    Because your assignments don't re-read from the intern pool and Java String(s) are immutable. Consider

    String str1 = new StringBuilder("计算机").append("软件").toString();
    String str1a = new String(str1); // <-- refers to a different String 
    str1 = str1.intern();
    str1a = str1a.intern();
    System.out.println(str1a == str1);
    String str2 = new StringBuffer("ja").append("va").toString();
    String str2a = new String(str2); // <-- refers to a different String 
    str2 = str2.intern();
    str2a = str2a.intern();
    System.out.println(str2a == str2);
    

    The output is (as you might expect)

    true
    true
    

提交回复
热议问题