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

后端 未结 4 2055
说谎
说谎 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 18:18

    The difference in behavior is unrelated to the differences between StringBuilder and StringBuffer.

    The javadoc of String#intern() states that it returns

    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    The String created from

    String str2 = new StringBuffer("ja").append("va").toString();
    

    is a brand new String that does not belong to the pool.

    For

    str2.intern() == str2
    

    to return false, the intern() call must have returned a different reference value, ie. the String "java" was already in the pool.

    In the first comparison, the String "计算机软件" was not in the string pool prior to the call to intern(). intern() therefore returned the same reference as the one stored in str2. The reference equality str2 == str2 therefore returns true.

提交回复
热议问题