实习生如何在以下代码中工作?

How does intern work in the following code?

String a = "abc";
String b = a.substring(1);
b.intern();
String c = "bc";
System.out.println(b == c);

这个问题可能很愚蠢,因为 intern 在这里没有主要用途,我仍然对这个事实感到困惑,为什么 b == c 结果 true.

何时

String b = a.substring(1)

被执行,字符串 b 引用具有 "bc"

的对象

b.intern是否在字符串常量池中创建了文字"bc",即使创建了,为什么b==c会导致true

查看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.

现在关注评论

    String b = a.substring(1);  // results "bc"
    b.intern();                 // check and places "bc" in pool
    String c = "bc";            // since it is a literal already presented in pool it gets the reference of it
    System.out.println(b == c);// now b and c are pointing to same literal

String b = a.substring(1); returns 包含 "bc" 的字符串实例,但此实例不是字符串池的一部分(默认情况下只有文字是驻留的,通过 new String(data) 创建的字符串和默认情况下,从 substringnextLine 等方法返回的方法不会被保留。

现在当你调用

b.intern();

此方法检查字符串池是否包含等于存储在 b(即 "bc")中的字符串,如果不是,则将该字符串放在那里。所以正弦在池中没有代表 "bc" 的字符串,它将把来自 b 的字符串放在那里。

所以现在字符串池包含 "abc""bc".

因为你打电话的时候

String c = "bc";

表示 bc 的字符串文字(与 b 参考中的相同)将从池中重用,这意味着 bc 将保留 相同实例

这证实了 b==c 的结果 returns true