Course contentsShow
← Java
Lesson 1136 of 2,87026. Map ImplementationsFree lesson

Consistent Ordering and equals Contract

How compareTo/compare must be consistent with equals to avoid unexpected Map behavior.

Consistent Ordering and equals Contract

You'll learn why compareTo() (or compare()) must agree with equals() to prevent strange Map behavior.

The Core Problem

When you use TreeMap, it relies entirely on compareTo() or your Comparator's compare() method to determine if two keys are "equal." It never calls equals(). This creates a serious issue: if your ordering method says two keys are equal (returns 0), but equals() says they're different, your Map will behave unexpectedly.

What "Consistent" Means

Two methods are consistent when:

  • If a.compareTo(b) == 0, then a.equals(b) must return true
  • If a.equals(b) returns true, then a.compareTo(b) must return 0

Think of it like two judges scoring a competition. If one judge says "these two are tied" but the other says "no, they're different," you get chaos.

The Consequences

Imagine a Person class where compareTo() only compares by age, but equals() compares age and name. You add two people with the same age but different names:

Person alice = new Person("Alice", 30);
Person bob = new Person("Bob", 30);

In a TreeMap, compareTo() returns 0 (same age), so TreeMap considers them duplicates. The second insertion overwrites the first, even though equals() says they're different people. You've lost Alice!

In contrast, a HashMap would correctly store both because it uses equals() and hashCode().

The Fix

Make your comparison logic match your equality logic. If age is the only thing that matters for equality, use it in both equals() and compareTo(). If multiple fields matter, include them consistently in both methods.

Key Takeaway: Always ensure compareTo() returns 0 if and only if equals() returns true, or TreeMap will silently treat unequal objects as duplicates.