我试图在类中重写equals和hashcode方法。它是另一个类的子类,它不实现equals方法和hashCode方法。
Eclipse发出了以下警告。
The super class ABC does not implement equals() and hashCode() methods.
The resulting code may not work correctly.
为什么给出上述警告?在什么情况下它可能无法正常工作?
答案 0 :(得分:5)
如果你说a.equals(b)
与b.equals(a)
,那么期望行为是相同的是合理的。但是如果它们具有通过继承相关的相应类型B
和A
,并且只有其中一个正确实现equals
,则这两个示例中的行为将有所不同。
此处,A
是超类,并且根本不实现equals
(因此它继承了java.lang.Object.equals
)。子类B
会覆盖equals
以依赖name
字段。
class A {
String name;
public A() {
this.name = "Fred";
}
}
class B extends A {
public boolean equals(Object o) {
A a = (A)o;
return a != null && a.name.equals(this.name);
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
B b = new B();
System.out.println(a.equals(b) == b.equals(a));
}
}
不出所料,输出为false
,因此为breaking symmetry。
答案 1 :(得分:0)
你是否尝试过超类覆盖等于...然后自动生成子类覆盖实现...
我相信它会有所不同。它将调用super.equals()
在当前自动生成的实现中,它只检查子类中的值..
考虑以下情况,您将了解警告的原因。
abstract Class A{
private int a;
public void setA(int a){
this.a=a;
}
}
Class B extends A{
private int x;
public void setX(int x){
this.x=x;
}
@Override
public boolean equals(Object obj) { // This does not call Super.equals
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
B other = (B) obj;
if (x != other.x)
return false;
return true;
}
}
并在主要方法中尝试
B b1= new B();
b1.setA(10);
b1.setX(20);
B b2= new B();
b2.setA(20);
b2.setX(20);
if(b1.equals(b2)){
System.out.println("Warning was Right");
}