From the JavaDoc of TreeMap :
Note that the ordering maintained by a sorted map (whether or not an
explicit comparator is provided) must be consistent with equals if
this sorted map is to correctly implement the Map interface. (See
Comparable or Comparator for a precise definition of consistent with
equals.) This is so because the Map interface is defined in terms of
the equals operation, but a map performs all key comparisons using its
compareTo (or compare) method, so two keys that are deemed equal by
this method are, from the standpoint of the sorted map, equal. The
behavior of a sorted map is well-defined even if its ordering is
inconsistent with equals; it just fails to obey the general contract
of the Map interface.
Can some one give an concrete example to demonsrate the problem that might occur if ordering is not consistent with equals ? Take for example User defined class that has a natural ordering i.e it implements Comparable . Also do all internal classes in JDK maintain this invariant?
The contract of the Comparable interface allows for non-consistent behaviour:
So in theory, it is possible that a class in the JDK had a
compareTonot consistent withequals. One good example is BigDecimal.Below is a contrived example of a comparator that is not consistent with equals (it basically says that all strings are equal).
Output: