gpt4 book ai didi

java - Java 中 new String ("X") 和 new String ("X") + new String ("Y") 之间字符串初始化的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:07:03 27 4
gpt4 key购买 nike

<分区>

public static void main(String[] args) {
String s1 = new String("aa");
s1.intern();
String s2 = "aa";
System.out.println(s1 == s2);

//wrong in JDK1.6 but true in JDK1.8
String str1 = new String("str") + new String("01");
str1.intern();
String str2 = "str01";
System.out.println(str1 == str2);

}

我用 JDK1.8 运行上面的代码,我想我会得到两个“错误”的结果,因为在我看来,很明显 s1 和 str1 位于堆中,而 s2 和 str2 被驻留在字符串池中,但我得到了一个“假”和一个“真”。问题来了:是什么导致了“真”?


以上是原始问题。现在确定这个问题与这些所谓的重复问题相去甚远,我想谈谈我的新发现:代码的第二部分在 JDK1.6 中得到“假”结果,而在 JDK1.8 中得到“真”结果。一些博客说在 JDK1.7 发布后,intern() 的行为发生了变化。

If the pool dosen't contain a string equals to this String object, this String object will not added to the pool and a reference to this String object will be added to the pool instead. It means the reference in the pool will be assigned to the string object located somewhere else(like the heap), and next time the initialization of a literal string equals the early one will also be assigned to the string object., which exactly describes the code part2 about the "true" result.

这个理论确实对我解释上面代码的结果有用。但很明显,该理论超出了 intern() 文档包含的内容,这在 JDK6/8 API 中几乎相同。


现在问题来了:对于JDK1.6和JDK 1.8中相同代码的不同结果有没有更好的解释?我上面提到的理论真的是这样吗?

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