在下面的代码中,
如果
s3
被注释掉,则s2==s2.intern()
的计算结果为true
。为什么?如果
s3
未注释,则s2==s2.intern()
的计算结果为false
。为什么?
我的理解是 concat()
方法总是返回一个新的字符串实例,即不是来自字符串池的实例。
public static void main(String[] args) {
String s2 = "hitesh".concat("yadav");
String s3 = "hiteshyadav";
System.out.println(Integer.toHexString(System.identityHashCode(s2)));
System.out.println(Integer.toHexString(System.identityHashCode(s2.intern())));
}
最佳答案
这是预期的行为。请注意以下事实:
- 当
intern()
实际执行字符串驻留时,其返回值与其参数相同; - 当
intern()
找到已驻留的字符串时,它会返回该实例而不是参数。
因此,当 s3
被注释掉时,s2
引用的 String 实例就是被实习的对象,并且 intern()
返回它。当 s3
存在时,这个预先存在的实例将由 intern()
返回。
要验证上述陈述并加深您的理解,请将以下行添加到您的代码中:
System.out.println(Integer.toHexString(System.identityHashCode(s3)));
你会发现第二行和第三行输出是相同的。
关于java - 如何从池或堆中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25853340/