Vin*_*C M 4 java equals hashcode
我试图在类中重写equals和hashcode方法.它是另一个类的子类,它不实现equals方法和hashCode方法.
Eclipse给出了以下警告.
The super class ABC does not implement equals() and hashCode() methods.
The resulting code may not work correctly.
Run Code Online (Sandbox Code Playgroud)
为什么给出上述警告?在什么情况下它可能无法正常工作?
如果你说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));
}
}
Run Code Online (Sandbox Code Playgroud)
不出所料,输出false因此破坏了对称性.
| 归档时间: |
|
| 查看次数: |
686 次 |
| 最近记录: |