equals
和hashCode
方法必须一致,这意味着当两个对象根据equals
方法相等时,它们的hashCode
方法应该返回相同的哈希值。
如果我们不重写 hashCode() 方法,Java 会返回一个唯一的哈希码。
class HashValue {
int x;
public boolean equals(Object oo) {
// if(oo instanceof Hashvalue) uncommenting ths gives error.dunno why?
// :|
HashValue hh = (HashValue) oo;
if (this.x == hh.x)
return true;
else
return false;
}
HashValue() {
x = 11;
}
}
class Hashing {
public static void main(String args[]) {
HashValue hv = new HashValue();
HashValue hv2 = new HashValue();
System.out.println(hv.hashCode());
System.out.println(hv2.hashCode());
if (hv.equals(hv2))
System.out.println("EQUAL");
else
System.out.println("NOT EQUAL");
}
}
为什么取消注释该行会产生编译错误?
如果对象具有不相等的哈希码,为什么即使默认哈希码不同,它们也显示为相等?