字符串新对象和比较
String new Object and comparision
据我所知,String 上的任何更改都会创建一个新对象,并且在某些 运行 时间 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
在上面的场景中,地址打印相同,但 == 运算符为假。
请说出为什么地址相同,比较错误。
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都指向同一个对象。我强烈建议你阅读实现
==
运算符用于参考比较。基本上,当您创建 s9
和 s11
时,只会在堆中创建 1 个对象。这就是为什么这 2 个哈希码相同并且 2 个不同的引用指向同一个对象。这就是 s9==s11
返回 false 的原因。
据我所知,String 上的任何更改都会创建一个新对象,并且在某些 运行 时间 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
在上面的场景中,地址打印相同,但 == 运算符为假。
请说出为什么地址相同,比较错误。
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都指向同一个对象。我强烈建议你阅读实现
==
运算符用于参考比较。基本上,当您创建 s9
和 s11
时,只会在堆中创建 1 个对象。这就是为什么这 2 个哈希码相同并且 2 个不同的引用指向同一个对象。这就是 s9==s11
返回 false 的原因。