Transitivity: If A > B and B > C, Then A > C
You'll learn why your compareTo method must obey the transitive property—and what breaks when it doesn't.
What Is Transitivity?
Transitivity is a mathematical property that must hold for any valid comparison method. It states: if object A is greater than B, and B is greater than C, then A must be greater than C.
In Java terms: if a.compareTo(b) > 0 and b.compareTo(c) > 0, then a.compareTo(c) must also return a positive value.
Why Does Transitivity Matter?
Sorting algorithms depend on transitivity to make decisions efficiently. They assume that if they've determined A > B and later find B > C, they can trust A > C without re-checking.
Think of it like a tournament bracket: if Player A beats Player B, and Player B beats Player C, you'd expect A to beat C. If that assumption fails, the tournament results become meaningless.
What Happens When You Violate Transitivity?
Violating transitivity creates logical contradictions:
Collections.sort()may produce incorrect orderingsTreeSetmight lose elements or throw exceptions- Binary search returns wrong results
- Your program becomes unpredictable
Example of violation: Imagine comparing Person objects where you return results based on random coin flips, or switching comparison criteria inconsistently. The method might say A > B and B > C, but then claim C > A—a circular contradiction.
The Rule
When you implement compareTo, ensure your logic is consistent across all comparisons. Use the same criteria every time, and make sure the relationships form a proper ordering.
Key Takeaway: Transitivity ensures that if A > B and B > C, then A > C—violating this contract breaks sorting algorithms and collection behavior, making your comparison logic unreliable.