Course contentsShow
← Java
Lesson 1070 of 2,87025. Set ImplementationsFree lesson

The Critical equals-compareTo Contract

Learn why compareTo consistency with equals matters in TreeSet and what breaks when they disagree.

The Critical equals-compareTo Contract

You'll learn why compareTo and equals must agree in TreeSet, and what breaks when they don't.

When you use a TreeSet, Java relies on compareTo() to organize elements in the tree structure. However, the Set interface promises that no duplicates exist—and "duplicate" traditionally means equals() returns true. This creates a contract: for TreeSet to work correctly, compareTo() must be consistent with equals().

What Does "Consistent" Mean?

Two objects should only be considered equal by compareTo() (returning 0) if they're also equal by equals() (returning true). When this breaks, TreeSet treats objects as duplicates based on compareTo alone, ignoring equals entirely.

The Problem When They Disagree

Imagine you have a Person class where compareTo() only compares age, but equals() compares both name and age. You create two people: Alice (age 30) and Bob (age 30).

  • alice.compareTo(bob) returns 0 (same age)
  • alice.equals(bob) returns false (different names)

If you add both to a TreeSet, it will only keep one! TreeSet uses compareTo to decide "these are the same," so Bob never gets added even though equals says they're different people. Your set loses data unexpectedly.

The Fix

Always ensure: if a.compareTo(b) == 0, then a.equals(b) must return true. Make both methods consider the same fields for comparison.

Key Takeaway:
In TreeSet, compareTo() must be consistent with equals()—objects that compare as equal (return 0) must also be equals(), or you'll get surprising duplicate-rejection behavior.