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:
It is strongly recommended (though not required) that natural orderings be consistent with equals.
So in theory, it is possible that a class in the JDK had a compareTo
not consistent with equals
. 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:
size: 1
content: {a=b}
public static void main(String[] args) {
Map<String, String> brokenMap = new TreeMap<String, String> (new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return 0;
}
});
brokenMap.put("a", "a");
brokenMap.put("b", "b");
System.out.println("size: " + brokenMap.size());
System.out.println("content: " + brokenMap);
}