Why it is implied that objects are equal if compareTo() returns 0?

前端 未结 6 1445
野趣味
野趣味 2020-12-16 12:03

Let\'s have a class Person. Person has a name and height.

Equals and hashCode() takes into account only name. Person is comparable (or we implement co

6条回答
  •  星月不相逢
    2020-12-16 12:47

    It is recommended that compareTo only returns 0, if a call to equals on the same objects would return true:

    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.

    (From the JDK 1.6 Javadocs)

提交回复
热议问题