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

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

    TreeSet doesn't operate using hash codes and equality - it only operates on the basis of the comparator you give it. Note that the Javadoc states:

    Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

    In your case, your comparison *isn't consistent with equals, so your set doesn't obey the general contract of Set.

    Why not just add more aspects to the comparison so that only equal elements compare with a result of 0?

提交回复
热议问题