String.intern() 显示奇怪的结果,它是如何工作的

String.intern() shows strange result, how does it work

我知道 String.intern() 如果不包含该对象,则将字符串添加到池中,但是如何解释结果。

代码如下:

public static void main(String[] args) {

        char[] abc = new char[]{'a','b','c'};
        String str = new String(abc);
        System.out.println(str == "abc");
        str.intern();
        System.out.println(str == "abc");
    }

输出为:

错误

错误

但是当代码如下:

public static void main(String[] args) {

        char[] abc = new char[]{'a','b','c'};
        String str = new String(abc);
        str.intern();
        System.out.println(str == "abc");
    }

输出为:

正确

有什么区别

不同之处在于,当您在显式调用 intern 之前使用 String 文字“abc”时,它会被隐式保留。

str.intern() 不会将 str 引用的实例存储在字符串池中,如果等于 String 已经在池中。

第一个片段:

System.out.println(str == "abc"); // "abc" is interned
str.intern(); // str is not stored in the pool
System.out.println(str == "abc"); // returns false

第二个片段:

str.intern(); // str is stored in the pool
System.out.println(str == "abc"); // returns true

来自 intern 的 Javadoc:

String java.lang.String.intern()

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... All literal strings and string-valued constant expressions are interned.