这里有一个类似的问题( Implementing equals method using compareTo ) - 最后建议重用 .compareTo()
来实现 .equals()
只要合约没有违反 - 我这里的重点是契约(Contract) x.equals(y) == y.equals(x)
。 .equals()
的简单实现将/可以是
public boolean equals(Object obj) {
return obj != null && (obj instanceof MyClass) && 0 == this.compareTo((MyClass)obj);
}
所以这是我的问题:当我有一个以这种方式实现它的 ParentClass
和一个扩展 ParentClass
的 ChildClass
时,我将拥有问题是 ChildClass
的实例也是 ParentClass
的实例,但反之则不然。
因此,对于 ParentClass
的实例 parent
和 ChildClass
的实例 child
至少是可能的 - 使用上面的 .equals()
- child.equals(parent) !=parent.equals(child)
。
那么如何使用.compareTo()
实现.equals()
并保证child.equals(parent) ==parent.equals(child)
?
有什么想法吗?谢谢。
编辑:这个问题的起源是SonarQube,它提示简单的实现不对称 - 上面的问题是我对SonarQube提示的解释。解决方案应该是对称的,但不应涉及太多变化。
最佳答案
仅使用 instanceof
进行相等性检查从根本上来说是不安全的。如果与子类的相等性没有意义,您需要使用 this.getClass().equals(other.getClass()) 来比较类的相等性。如果您想允许子类等于父类(这在许多情况下是无效的),您必须检查关系并委托(delegate)给子类。 parent 不可能知道平等的正确定义。
class Parent {
boolean equals(Object other) {
if (! other instanceof Parent) return false
if (! other.getClass().equals(Parent.class)) return other.equals(this);
// Otherwise compare two objects that precisely have the type Parent
}
}
请注意,如果 child 不是最终的,您还必须(适本地)对 child 这样做。在子 equals 中,您可以允许另一个是 Parent
的实例(但您确实需要适本地比较相等性)。
关于java - 在 Java 中使用 .compareTo() 时如何使 .equals() 对称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38183235/