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

Symmetry: sgn(x.compareTo(y)) == -sgn(y.compareTo(x))

Learn why reversing comparison order must flip the sign and what happens when it doesn't.

Symmetry: The Mirror Rule of Comparison

You'll learn why reversing the order of comparison must flip the sign, and what breaks when it doesn't.

The Core Idea

Symmetry in compareTo means that if you swap the two objects being compared, the result must flip its sign. If x.compareTo(y) returns a positive number (meaning x > y), then y.compareTo(x) must return a negative number (meaning y < x). If x.compareTo(y) returns zero, y.compareTo(x) must also return zero.

Think of it like a seesaw: if Alice is heavier than Bob, then Bob must be lighter than Alice. The relationship is perfectly mirrored.

Why It Matters

Breaking symmetry creates logical contradictions. Imagine if your compareTo implementation said "A is greater than B" but also "B is greater than A" when you swap the order. Sorting algorithms would produce unpredictable results, TreeSet might lose elements, and binary searches could fail entirely.

The Mathematical Notation

The contract states: sgn(x.compareTo(y)) == -sgn(y.compareTo(x))

Here, sgn() means "sign of" — it returns -1 for negative, 0 for zero, or +1 for positive. The equation says: the sign of comparing x to y must be the opposite of comparing y to x.

Common Violation

A broken implementation might return 1 when x > y but also return 1 when y > x. This violates symmetry because both directions claim to be "greater."

Key Takeaway: Symmetry ensures comparison is a consistent two-way street—if x relates to y one way, y must relate to x in the exact opposite way, or sorting and ordered collections will malfunction.