为什么重写equals时还必须重写hashcode方法
先看一个例子
A
package other.equals;
public class A {
@Override
public boolean equals(Object obj) {
return true;
}
}
B
package other.equals;
public class B {
@Override
public int hashCode() {
return 1;
}
}
C
package other.equals;
public class C {
@Override
public int hashCode() {
return 2;
}
@Override
public boolean equals(Object obj) {
return true;
}
}
测试类
HashSetTest
package other.equals;
import java.util.HashSet;
public class HashSetTest {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new A());
hashSet.add(new A());
hashSet.add(new B());
hashSet.add(new B());
hashSet.add(new C());
hashSet.add(new C());
for (Object hs : hashSet) {
System.out.println(hs);
}
// HashSet重写了toString()方法
// System.out.println(hashSet);
}
}
运行结果
other.equals.B@1
other.equals.B@1
other.equals.C@2
other.equals.A@15db9742
other.equals.A@6d06d69c
其中,只有当equals返回true,且hashcode值相同时,认为两个对象相同
简单理解为以下图
equals返回true,且hashcode值相同时
即:
(1)当obj1.equals(obj2)为true时,obj1.hashCode() == obj2.hashCode()必须为true
(2)当obj1.hashCode() == obj2.hashCode()为false时,obj1.equals(obj2)必须为false