java中==,equals和hashcode的示例 [英] Example of ==, equals and hashcode in java
本文介绍了java中==,equals和hashcode的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于此:
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
这里 ==
为每个对象赋予false但每个对象的哈希码String对象是一样的。为什么会这样?
Here ==
is giving false for each object but the hashcode for each String object is same. Why is it so?
推荐答案
==
确实比较了对象(我的意思是 - 两个引用都指向同一个对象),而不是它们的内容,而 .equal
比较内容(至少对于String)。
==
does compare real equality of objects (I mean - both references point to the same object), not their content, whereas .equal
compares content (at least for String).
String a = new String("aa");
String b = new String("aa");
a
和 b
指向不同的对象。
还要注意,如果对象相等,那么它们的hashchodes必须相同,但如果hashcode是相同的,这并不意味着对象是平等的。
Notice also that if objects are equal then their hashchodes must be the same, but if hashcodes are the same, it doesn't mean that objects are equal.
这篇关于java中==,equals和hashcode的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文