加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 使用compareTo实现equals方法

发布时间:2020-12-14 23:55:05 所属栏目:Java 来源:网络整理
导读:一般问题:在 Java中实现一个默认equals方法的覆盖时,应该如何使用已经实现的compareTo方法来将独立逻辑写入equals方法呢?我注意到有人在另一个问题中提到foo.equals((String)null)返回false,而String.compareTo((String)null)抛出一个NullPointerException
一般问题:在 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()方法的合同.如果他们不相互冲突,那么继续.

我认为执行合同更重要.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读