Course contentsShow
← Java
Lesson 1336 of 2,87030. Comparable and ComparatorFree lesson

Comparator Stability and Equals Consistency

Understand why Comparators should be consistent with equals and how sort stability is affected by comparison logic.

Comparator Stability and Equals Consistency

You'll learn why Comparators should align with equals and how this affects sort stability.

When you implement a Comparator, you're defining a custom ordering. But here's the catch: if your Comparator returns zero for two objects (meaning they're "equal" for sorting purposes), ideally those objects should also be equal according to their equals method. This is called equals consistency.

Why Equals Consistency Matters

Imagine sorting Person objects by age only. Two people with the same age would compare as equal (compare returns 0), but they're clearly different people. This breaks equals consistency because person1.equals(person2) would return false.

The impact? Data structures like TreeSet and TreeMap rely on comparisons to determine uniqueness. If your Comparator says two objects are equal but equals disagrees, you might accidentally overwrite distinct objects or get unpredictable behavior.

Sort Stability

Stability means elements that compare as equal maintain their original relative order after sorting. Java's Collections.sort and Arrays.sort are guaranteed to be stable for reference types.

However, if your Comparator is inconsistent with equals, you might not notice stability working as expected. For example, if two Person objects with age 30 are considered "equal" by your comparator but not by equals, they'll stay in their original order—but it may look arbitrary since they're truly different objects.

Best Practice

Break ties meaningfully! If comparing by age, add a secondary comparison (like name) to ensure your Comparator produces a total ordering that respects object identity:

Comparator<Person> byAge = (p1, p2) -> {
    int ageCompare = Integer.compare(p1.getAge(), p2.getAge());
    if (ageCompare != 0) return ageCompare;
    return p1.getName().compareTo(p2.getName()); // tie-breaker
};

Key Takeaway: Comparators should be consistent with equals when possible, and always define a complete ordering (break ties) to leverage sort stability and avoid surprises in sorted collections.