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

前端 未结 6 1450
野趣味
野趣味 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:32

    It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)) [1]

    So it's fine that you compare with a different criteria than the used on equals granted that you document it.

    However it would be better if your compare by the same criteria and if needed provide a custom comparator which works on the new criteria ( height in the case of Person )

提交回复
热议问题