鉴于这种:
String s1= new String("abc");
String s2= new String("abc");
String s3 ="abc";
System.out.println(s1==s3);
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
输出是:
false
false
true
true
96354
96354
96354
Here ==
为每个对象提供 false,但每个 String 对象的哈希码是相同的。为什么会这样呢?
==
确实比较真正的平等objects(我的意思是 - 两个引用都指向同一个对象),而不是它们的内容,而.equal
比较内容(至少对于字符串)。
String a = new String("aa");
String b = new String("aa");
a
and b
分别指向不同的对象。
还要注意,如果对象相等,那么它们的 hashchodes 必须相同,但如果 hashcode 相同,并不意味着对象相等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)