Inconsistent compareTo and equals in TreeSet
You'll learn: How a mismatch between compareTo and equals can cause TreeSet to silently lose elements you expected it to store.
The Problem
Remember that TreeSet uses compareTo (not equals) to determine element uniqueness. If your class implements both methods but they contradict each other, TreeSet will behave unexpectedly—often treating distinct objects as duplicates.
The scenario: Imagine two Person objects are considered equal by equals (same name), but compareTo only checks age. Or vice versa—equals checks age, but compareTo checks name. This inconsistency confuses TreeSet.
What Happens
When you add an element, TreeSet navigates its internal tree structure using compareTo to find where it belongs. If compareTo returns 0 (meaning "these are equivalent"), TreeSet refuses to add the new element, assuming it's a duplicate—even if equals would return false.
class Person implements Comparable<Person> {
String name;
int age;
public boolean equals(Object o) {
Person p = (Person) o;
return this.name.equals(p.name); // equals checks name
}
public int compareTo(Person p) {
return this.age - p.age; // compareTo checks age only
}
}
TreeSet<Person> set = new TreeSet<>();
set.add(new Person("Alice", 30));
set.add(new Person("Bob", 30)); // compareTo returns 0!
// Bob is NOT added! TreeSet thinks it's a duplicate.
Even though "Alice".equals("Bob") is false, TreeSet sees compareTo return 0 and rejects Bob.
The Fix
Make compareTo consistent with equals: compare the same fields in both methods. If equals checks name and age, compareTo should too.
Key Takeaway: When compareTo and equals disagree, TreeSet silently drops elements, creating hard-to-debug bugs. Always ensure compareTo reflects the same equality logic as equals.