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.
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
- If you override equals but not hashCode, what breaks and when?mediumAlso on object-semantics4 min
- Envelopes nest only when both width and height are strictly larger. How many can you nest, and why must equal widths be sorted by height descending?hardAlso on sorting4 min
- Shipping packages within D days minimises a maximum. Now place m sensors at fixed positions so the closest pair is as far apart as possible. What changes in the binary search?mediumAlso on sorting5 min
- How does HashMap work internally, and what happens when it resizes?mediumAlso on collections3 min