java – 使用compareTo实现equals方法

一般问题:在Java中实现一个默认equals方法的覆盖时,应该如何使用已经实现的compareTo方法来将独立逻辑写入equals方法呢?我注意到有人在另一个问题中提到foo.equals((String)null)返回false,而String.compareTo((String)null)抛出一个NullPointerException.使这些不一致的结果成为理想的功能?

样本等于方法:

@Override
public boolean equals(Object obj) {
    if (obj != null && obj instanceof MyClass) {
        MyClass msg = (MyClass)obj;
        return this.compareTo(msg) == 0;
    }
    return false;
}

编辑:
Comparable的文档引用

The natural ordering for a class C is said to be consistent with
equals if and only if e1.compareTo(e2) == 0 has the same boolean value
as e1.equals(e2) for every e1 and e2 of class C. Note that null is not
an instance of any class, and e.compareTo(null) should throw a
NullPointerException even though e.equals(null) returns false

编辑:

经过进一步审查,我发现注意到,Comparable文件还说明如下:

The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

Ergo,因为null.compareTo(x)显然会抛出一个NPE,x.compareTo(null)也应该抛出一个NPE.而对于平等而言,情况并非如此.对于NPE的正确处理我很大,所以我觉得这个比较重要.

最佳答案
equals()和compareTo()之间的区别是equals()只是检查两个对象是否相等,其中compareTo()用于标识指定类的实例的自然顺序.还有equals()方法与hashCode()方法有一个契约,但compareTo()没有.

根据JavaDoc

Note that null is not an instance of any class, and e.compareTo(null)
should throw a NullPointerException even though e.equals(null) returns
false.

It is strongly recommended, but not strictly required that
(x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class
that implements the Comparable interface and violates this condition
should clearly indicate this fact. The recommended language is “Note:
this class has a natural ordering that is inconsistent with equals.”

您可以随意在equals()方法中重用compareTo()方法逻辑,但请记住所有与equals(),hashCode()的合约以及来自JavaDoc for compareTo()方法的合同.如果他们不相互冲突,那么继续.

我认为执行合同更重要.

转载注明原文:java – 使用compareTo实现equals方法 - 代码日志