gpt4 book ai didi

java - 如何从池或堆中查找字符串

转载 作者:行者123 更新时间:2023-12-01 12:32:10 25 4
gpt4 key购买 nike

在下面的代码中,

  1. 如果 s3 被注释掉,则 s2==s2.intern() 的计算结果为 true。为什么?

  2. 如果 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())));
}

最佳答案

这是预期的行为。请注意以下事实:

  1. intern()实际执行字符串驻留时,其返回值与其参数相同;
  2. intern() 找到已驻留的字符串时,它会返回该实例而不是参数。

因此,当 s3 被注释掉时,s2 引用的 String 实例就是被实习的对象,并且 intern() 返回它。当 s3 存在时,这个预先存在的实例将由 intern() 返回。

要验证上述陈述并加深您的理解,请将以下行添加到您的代码中:

System.out.println(Integer.toHexString(System.identityHashCode(s3)));

你会发现第二行和第三行输出是相同的。

关于java - 如何从池或堆中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25853340/

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