gpt4 book ai didi

java - String new Object 和比较

转载 作者:行者123 更新时间:2023-11-30 06:11:02 25 4
gpt4 key购买 nike

据我所知,字符串上的任何更改都会创建一个新对象,对于某些运行时 Activity ,如果内容发生更改,则会在堆中创建一个新对象,但我对以下情况感到困惑,请给出想法...

String s8="abcd";
String s9=s8.toUpperCase();
String s11=s8.toUpperCase();
System.out.println("S9 "+s9.hashCode() +" s10 "+s11.hashCode());//S9 -- 2001986 s10 -- 2001986
System.out.println(s9==s11);//false

在上述场景中,地址打印相同,但 == 运算符显示 false。

请说明为什么地址相同而比较错误。

最佳答案

String s8="abcd"; : Memory will be allocated from constant pool.

String s9=s8.toUpperCase(); New object will be created on heap

String s11=s8.toUpperCase(); Another New object will be created on heap

如果你看看toUpperCase的实现

public String toUpperCase(Locale locale) {

..

return new String(result, 0, len + resultOffset);

因此它每次都会在堆上创建一个新对象。因此 s9 != s11

Note: If two objects are equal then their hashcodes are equal but vice versa is not true

更新:

String s11=s9.toUpperCase();
s11==s9 // returns true

因为没有可以修改的字符,因此s11和s9都指向同一个对象。我强烈建议您阅读实现

关于java - String new Object 和比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50226348/

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