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

TreeSet's Reliance on compareTo, Not equals

Understand that TreeSet uses compareTo for ordering and duplicate detection, not equals or hashCode.

TreeSet's Reliance on compareTo, Not equals

What you'll learn: How TreeSet uses compareTo for both ordering and duplicate detection, completely ignoring equals and hashCode.

The Core Difference

Unlike HashSet, which relies on equals() and hashCode() to detect duplicates, TreeSet uses only the compareTo() method from the Comparable interface (or a custom Comparator). If compareTo() returns 0, TreeSet treats two objects as duplicates—even if their equals() method would return false.

This means TreeSet doesn't care about your equals() or hashCode() implementations at all.

Why This Matters

Imagine you have a Person class where compareTo sorts by age, but equals checks if names match. To TreeSet, two people with the same age are the same person, and it will keep only one:

class Person implements Comparable<Person> {
    String name;
    int age;
    
    public int compareTo(Person other) {
        return Integer.compare(this.age, other.age); // Only compares age
    }
    
    public boolean equals(Object o) {
        // Compares name (but TreeSet ignores this!)
        Person p = (Person) o;
        return this.name.equals(p.name);
    }
}

TreeSet<Person> set = new TreeSet<>();
set.add(new Person("Alice", 25));
set.add(new Person("Bob", 25));    // Rejected! compareTo returns 0
System.out.println(set.size());    // Prints 1, not 2

Bob is rejected because his compareTo result (comparing ages) is 0 when compared to Alice.

The Golden Rule

For consistent behavior across all collections, compareTo should align with equals: x.compareTo(y) == 0 should return true whenever x.equals(y) is true.

Key Takeaway: TreeSet uses compareTo() exclusively for ordering and duplicate detection—your equals() and hashCode() methods are completely ignored.