为什么即使我的散列码值相同,'=='也会返回false [英] why '==' is returning false even after my hashcode value is same
问题描述
我写了一个类,如
public class HashCodeImpl {
public int hashCode(){
返回1;
public static void main(String [] args){
// TODO自动生成的方法存根
HashCodeUtil h = new HashCodeUtil( );
HashCodeUtil h1 = new HashCodeUtil();
System.out.println(h.hashCode());
System.out.println(h1.hashCode());
System.out.println(h);
System.out.println(h1);
System.out.println(h == h1);
}
}
OutPut:
1
com.manu.test.HashCodeUtil@1
com.manu.test.HashCodeUtil@1 false
我的问题是:当我的hashCode方法返回相同的值时,为什么
System.out。 println(h == h1);
即将到期假?
请解释。
因为它们是两个不同的对象引用。 ==
比较引用,而不是 hashCode
结果。
<为了得到想要的结果,你可以重写你的类中的
equals
方法并使用 h1.equals(h2)
看看它们是否相同。在这里,您可以使用 hashCode
的结果来简化对被比较对象的相等性的评估(这并不意味着具有相同哈希代码的两个对象是相等的) 。但请注意,即使对象具有相同的
hashCode
,并且与等于
方法,它们是在堆中占据不同位置的不同引用。 I have a written a class like
public class HashCodeImpl{
public int hashCode(){
return 1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
HashCodeUtil h= new HashCodeUtil();
HashCodeUtil h1= new HashCodeUtil();
System.out.println(h.hashCode());
System.out.println(h1.hashCode());
System.out.println(h);
System.out.println(h1);
System.out.println(h==h1);
}
}
OutPut:
1
com.manu.test.HashCodeUtil@1
com.manu.test.HashCodeUtil@1 false
My question is: when my hashCode method is returning same value then why
System.out.println(h==h1);
is coming false?
Please explain.
Because they are two different object references. ==
compare the references, not the hashCode
results.
To get a desired result, you may override the equals
method in your class and use h1.equals(h2)
to see if they're equivalent. Here you may use the result of hashCode
to ease the evaluation of the equality of the objects being compared (this doesn't mean that two objects with the same hash code are equals).
But note that even if the objects have the same hashCode
and are equivalent by the definition of the equals
method, they are different references that occupy a different place in the heap.
这篇关于为什么即使我的散列码值相同,'=='也会返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!