gpt4 book ai didi

java - String#intern 对实习生结果的困惑

转载 作者:行者123 更新时间:2023-11-30 07:47:16 25 4
gpt4 key购买 nike

public class Main {
public static void main(String[] args) {
String a = new String("11") ;
a.intern();
String b = "11";
System.out.println(a == b); // false

String c = new String("2") + new String("2");
c.intern();
String d = "22";
System.out.println(c == d); // true
}
}

打印:

false
true

我在 jkd 1.8 上运行它。我很困惑为什么第二个 println 结果。

最佳答案

String 字面值总是在第一次出现时自动保留。您的代码中的 String 文字是“11”和“2”。

另一方面,作为 String 连接结果创建的 String 不会自动驻留。

String a = new String("11"); // interns the String literal "11", and creates a
// different String instance referenced by a
a.intern(); // doesn't add a to the String pool, since "11" is already in
// the String pool
String b = "11"; // "11" returns the canonical instance already in the pool,
// which is != a

因此 a != b

String c = new String("2") + new String("2"); // interns the String "2", creates 2 
// more Strings having the same value,
// and creates an additional String
// whose value is "22", which is not
// interned yet
c.intern(); // c is added to the String pool as the canonical instance whose value
// is "22"
String d = "22"; // "22" returns the canonical instance already in the pool,
// which is == c

因此 c == d

以上所有内容均来自 intern 的 Javadoc:

Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String.

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.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.

关于java - String#intern 对实习生结果的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com