public static void main(String[] args) {
String str1 = new StringBuilder("计算机").append("软件").toString();
System.out.println(str1.intern() == str1);
String str2 = new StringBuffer("ja").append("va").toString();
System.out.println(str2.intern() == str2);
}
结果:
true
false
第一个打印true
,第二个打印false
。为什么结果不同?
最佳答案
行为上的差异与 StringBuilder
和 StringBuffer
之间的差异无关。
String#intern()
的 javadoc声明它返回
When the intern method is invoked, if the pool already contains a string equal to this
String
object as determined by theequals(Object)
method, then the string from the pool is returned. Otherwise, thisString
object is added to the pool and a reference to thisString
object is returned.
从
创建的String
String str2 = new StringBuffer("ja").append("va").toString();
是一个全新的String
,不属于该池。
为了
str2.intern() == str2
要返回 false
,intern()
调用必须返回不同的引用值,即。 String
"java"
已经在池中。
在第一个比较中,String
“计算机软件”在调用 intern()
之前不在字符串池中。 intern()
因此返回与存储在 str2
中的相同的引用。引用等式 str2 == str2
因此返回 true
。
关于java - 为什么这些字符串的 str == str.intern() 的结果不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32000960/