Skip to content
Preptima
mediumConceptCodingMidSeniorStaff

Sorting a list throws IllegalArgumentException saying the comparison method violates its general contract. What did the comparator get wrong?

The sort detected that your comparator contradicted itself partway through a merge. The usual causes are a subtraction that overflows, an ordering that is not transitive, and a sort key that changes while the sort is running. Use this collections answer to show the decision, trade-off, and evidence rather than a memorised definition. It also connects sorting to the point an interviewer is testing.

5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive

Answer

Short answer

A Java comparator contract violation means compare(a, b) is not defining a stable, transitive order. The common bugs are subtracting numbers and overflowing, returning inconsistent tie-breaks, or reading a mutable sort key while the list is being sorted. The fix is to express the order with Comparator.comparing(...).thenComparing(...) or Integer.compare, then test antisymmetry and transitivity directly.

Was this answer helpful?

Likely follow-ups

  • Why does a TreeMap given the same broken comparator lose entries instead of throwing?
  • What does it mean for a sort to be stable, and which sorts in java.util keep that property?
  • Comparator.comparing on a field that is sometimes null throws. How do you order nulls without a null check in every comparator?
  • What is -Djava.util.Arrays.useLegacyMergeSort=true for, and why is it not a fix?

Related questions

Further reading

Related Topics