Search code examples
javaequalstreemapcompareto

Unconsistent natural ordering for TreeMap


Is it possible to create a TreeMap in which the natural ordering of the keys is not consistent(key1.equals(key2) = true, key1.compareTo(k3) = 1, key2.compareTo(key3) = -1)? If I will change the compareTo so that this won't happen but there will be keys where key1.equals(key2) = false but key1.compareTo(key2)=0 will it be good?


Solution

  • You'll get unpredictable behaviour as you'll be using the TreeMap outside of its declared constraints.

    The Map interface is declared to rely on the equals() method, and the TreeMap to rely on compareTo(). So both methods are relevant and should be consistent, otherwise you can't rely on the outcome. Even if it works in some JVM version / implementation, it might break in a different one.

    Technically, the TreeMap uses the compareTo() method, so you might get away with a compareTo() that's ok in itself, only incompatible with equals(), but I surely won't recommend that!