为什么这些字符串的str == str.intern()结果不同? [英] Why are the results of of str == str.intern() for these strings different?
问题描述
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
。为什么结果不同?
First one prints true
, and the second prints false
. Why are the results different?
推荐答案
行为上的差异与 StringBuilder之间的差异无关
和 StringBuffer
。
String #intern()
表明它返回
The javadoc of String#intern()
states that it returns
调用实习方法时,如果池已包含等于此<$ c的
字符串$ c> String 由equals(Object)
方法确定的对象,然后返回池中的字符串。否则,此
String
对象将添加到池中,对此String的引用
对象被返回。
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
已创建from
String str2 = new StringBuffer("ja").append("va").toString();
是一个全新的字符串
属于游泳池。
is a brand new String
that does not belong to the pool.
对于
str2.intern() == str2
返回 false
, intern()
调用必须返回不同的参考值,即。 字符串
java
已经在池中。
to return false
, the intern()
call must have returned a different reference value, ie. the String
"java"
was already in the pool.
在第一次比较中, String
计算机软件不在调用的字符串池之前到 intern()
。 intern()
因此返回与 str2
中存储的引用相同的引用。引用相等 str2 == str2
因此返回 true
。
In the first comparison, the String
"计算机软件" was not in the string pool prior to the call to intern()
. intern()
therefore returned the same reference as the one stored in str2
. The reference equality str2 == str2
therefore returns true
.
这篇关于为什么这些字符串的str == str.intern()结果不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!