Strange behavior with string interning in Java

后端 未结 4 1658
别跟我提以往
别跟我提以往 2020-12-14 10:21

There is code as following:

String s = new String(\"1\");
s.intern();
String s2 = \"1\";
System.out.println(s == s2);

String s3 = new String(\"1\")+new          


        
4条回答
  •  轮回少年
    2020-12-14 11:02

    Here's what's happening:


    Example 1

    String s1 = new String("1"); 
    s1.intern();
    String s2 = "1";
    
    1. The string literal "1" (passed into the String constructor) is interned at address A.
      String s1 is created at address B because it is not a literal or constant expression.
    2. The call to intern() has no effect. String "1" is already interned, and the result of the operation is not assigned back to s1.
    3. String s2 with value "1" is retrieved from the string pool, so points to address A.

    Result: Strings s1 and s2 point to different addresses.


    Example 2

    String s3 = new String("1") + new String("1");
    s3.intern();
    String s4 = "11";
    
    1. String s3 is created at address C.
    2. The call to intern() adds the string with value "11" at address C to the string pool.
    3. String s4 with value "11" is retrieved from the string pool, so points to address C.

    Result: Strings s3 and s4 point to the same address.


    Summary

    String "1" is interned before the call to intern() is made, by virtue of its presence in the s1 = new String("1") constructor call.

    Changing that constructor call to s1 = new String(new char[]{'1'}) will make the comparison of s1 == s2 evaluate to true because both will now refer to the string that was explicitly interned by calling s1.intern().

    (I used the code from this answer to get information about the strings' memory locations.)

提交回复
热议问题