我正在深入学习哈希码,并发现以下内容:
1. 如果你重写了equals()方法,你必须同时重写hashcode()方法。
2. 要判断两个对象是否为同一对象,请使用==运算符。
考虑到这两个因素,在Java中,当使用==运算符
比较两个实例是否相同时,
if(object1 == object2)
实际上正在进行的是
if(object1.hashcode() == object2.hashcode())
但是通过运行下面的测试,我发现我错了。
public class Main {
public static void main(String[] args){
Obj1 one = new Obj1();
Obj1 two = new Obj1();
//is this calling hashCode() in backend???
if(one == two) {
System.out.println("same");
}
else {
System.out.println("nope");
}
//this is of course return true
if(one == one) {
System.out.println("one and one is same");
}
}
}
class Obj1 {
@Override
public int hashCode() {
System.out.println("hashCode() is called");
return 111;
}
@Override
public boolean equals(Object another) {
System.out.println("equals() is called");
return false;
}
}
根据使用
== 运算符
进行的测试,并且没有调用 equals()
方法。因此,我的问题是如果可以使用 == 运算符
来比较对象是否相同,那么为什么要重写 equals()
和 hashCode()
方法进行比较?难道 == 运算符
已经完成了这个工作吗?参考文献: Overriding hashCode() - is this good enough? http://mindprod.com/jgloss/hashcode.html http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)