假设有两个这样的类:
abstract class A { /* some irrelevant methods */ }
class B extends A {
public final int x;
public B(final int x) {
this.x = x;
}
/* some more irrelevant methods */
}
然后我使用 Eclipse 的“Source → Generate hashCode() and equals”在类 B
上生成 equals()
和 hashCode()
方法()……”。但 Eclipse 警告我:
The super class 'com.example.test2.A' does not redeclare equals() and hashCode() - the resulting code may not work correctly.
那么,什么会导致生成的代码无法与生成的方法一起正常工作?
(顺便说一句,生成的方法如下所示:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
return result;
}
@Override
public boolean equals(Object obj) {
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;
}
)
最佳答案
在重写 equals 时必须小心以遵守一组特定的规则。见 javadoc详情。简而言之,两个棘手的部分是保持对称性和传递性。根据 Joshua Block 的 Effective Java
"There is no way to extend an instantiable class and add a value component while preserving the equals contract"
这是什么意思?好吧,假设您在 A 类中有一个类型为 T 的属性,而在子类 B 中有另一个类型为 V 的属性。如果两个类都覆盖等于,那么将 A 与 B 进行比较而不是 B 与 A 进行比较时,您将得到不同的结果。
A a = new A(T obj1);
B b = new B(T obj1, V obj2);
a.equals(b) //will return true, because objects a and b have the same T reference.
b.equals(a) //will return false because a is not an instanceof B
这是违反对称性的。如果您尝试通过混合比较来纠正此问题,您将失去传递性。
B b2 = new B(T obj1, V obj3);
b.equals(a) // will return true now, because we altered equals to do mixed comparisions
b2.equals(a) // will return true for the same reason
b.equals(b2) // will return false, because obj2 != obj3
在这种情况下 b == a, b2 ==a, b != b2,这是一个问题。
编辑
为了更准确地回答这个问题:“什么会导致生成的代码无法与生成的方法一起正常工作”,让我们考虑一下这个具体情况。父类是抽象的,不会覆盖equals。我相信我们可以得出结论,代码是安全的,没有发生违反 equals 合约的情况。这是父类是抽象的结果。它不能被实例化,因此上面的例子不适用于它。
现在考虑父类是具体的并且不覆盖equals的情况。正如 Duncan Jones 所指出的,警告消息仍然会生成,在这种情况下这样做似乎是正确的。默认情况下,所有类都从 Object 继承 equals,并将根据对象标识(即内存地址)进行比较。如果与覆盖 equals 的子类一起使用,这可能会导致不对称比较。
A a = new A();
B b = new B(T obj1);
a.equals(b) //will return false, because the references do not point at the same object
b.equals(a) //should return false, but could return true based on implementation logic.
如果 b.equals(a) 出于任何原因返回 true,无论是实现逻辑还是编程错误,都会导致失去对称性。编译器无法强制执行此操作,因此会生成警告。
关于java - 父类(super class)不重新声明equals()和hashCode()会出什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16236708/