一般问题:在 Java 中实现默认 equals
方法的重写时,对于简单地使用已经实现的 compareTo
方法与将独立逻辑写入其中,我应该注意什么?等于方法?我注意到有人在另一个问题中提到 foo.equals((String)null)
返回 false 而 String.compareTo((String)null)
抛出 NullPointerException
。是什么让这些不一致的结果成为理想的功能?
示例 equals
方法:
@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.)
因此,因为 null.compareTo(x)
显然会抛出 NPE , x.compareTo(null)
也应该抛出 NPE。而对于 equals,则不一定如此。我非常重视正确处理 NPE,所以我觉得这相对重要。
最佳答案
compareTo
可能 涉及比获得相等答案所必需的更多的工作,这可能最终成为性能问题,取决于您的应用程序使用情况。
除此之外,关注 DRY原则上,按照您的建议重新使用代码是个好主意。
关于java - 使用 compareTo 实现 equals 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16816827/