Video in progress
When does "Comparison method violates its general contract!" appear, and how do you track it down?
When TimSort inside List.sort/Arrays.sort notices contradictory comparator results, it throws an IllegalArgumentException. Causes: a transitivity violation, a - b overflow, a field that changes during the sort, wrong null handling, or returning a random value.
📖 Answer
A comparator must obey three rules: sgn(compare(a,b)) == -sgn(compare(b,a)), transitivity (a>b, b>c ⇒ a>c), and if compare(a,b)==0, then a and b must relate to everything else in the same way.
Real cases:
// 1. overflow
(a, b) -> a.getId() - b.getId(); // the sign flips when ids are large
// 2. handling null on one side only
(a, b) -> a.getDate() == null ? -1 : a.getDate().compareTo(b.getDate());
// if b.getDate() == null: an NPE or asymmetry
// 3. "roughly equal"
(a, b) -> Math.abs(a.price - b.price) < 0.01 ? 0 : Double.compare(a.price, b.price);
// not transitive: 1.000 ≈ 1.009 ≈ 1.018, but 1.000 < 1.018
The error only appears with data in a certain order and of a certain size (usually more than 32 elements), which is why it passes in tests and blows up on prod.
How to find it: log the list that caused the error and replay it locally; write a property-based test for the comparator that checks transitivity and antisymmetry on random triples. The fix is almost always to switch to ready-made building blocks like Comparator.comparing(...), comparingLong and nullsFirst.
People used to "hide" this error with -Djava.util.Arrays.useLegacyMergeSort=true. That doesn't solve the problem; it just makes it invisible.
Sign up to mark studied questions and save your progress.