四楼一米五 2021-07-29 12:05 采纳率: 0%
浏览 13

intern()后结果为何是false?


String str2 = new String("str")+new String("01");
String str1 = "str01";
str2.intern();
System.out.println(str2==str1);
  • 写回答

1条回答 默认 最新

  • 葡萄城技术团队 葡萄城官方账号 2021-07-29 12:10
    关注

    来看一眼intern()这个方法
    注意这一段:

    When the intern method is invoked, if the pool already contains a string equal to this {@code String} object as determined by the {@link #equals(Object)} method, then the string from the pool is returned. Otherwise, this {@code String} object is added to the pool and a reference to this {@code String} object is returned.

    翻译过来的意思是:

    当intern方法被调用时,如果常量池中已经包含了一个字符串,该字符串等于这个对象,那么池中的字符串将被返回。否则,该对象将被添加到池中,并返回对该对象的引用。

    其实,intern()是一个Native方法,底层调用C++的 StringTable::intern方法实现。当通过语句str.intern()调用intern()方法后,JVM 就会在当前类的常量池中查找是否存在与str等值的String,若存在则直接返回常量池中相应Strnig的引用;若不存在,则会在常量池中创建一个等值的String,然后返回这个String在常量池中的引用。因此,只要是等值的String对象,使用intern()方法返回的都是常量池中同一个String引用,所以,这些等值的String对象通过intern()后使用==是可以匹配的。

    其实严格来说,上面那段代码在JDK1.6中,会得到两个false;而在JDK1.7及之后中运行,则会得到一个false和一个true。

    详细查看:https://blog.csdn.net/jcSongle/article/details/108271921

    评论

报告相同问题?

问题事件

  • 创建了问题 7月29日

悬赏问题

  • ¥30 模拟电路 logisim
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价