我知道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”时,它是隐式的intern。
str.intern()
如果一个相等的 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
来自实习生的 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.
关于java - String.intern() 显示奇怪的结果,它是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65575039/