Quick revision
The short answer
a.getId() - b.getId() overflows when the two IDs are far apart with different signs: for example 2,000,000,000 minus -1,000,000,000 is 3,000,000,000, which does not fit in an int and wraps to a negative number, so the comparator says the larger ID is smaller. Use Integer.compare(a.getId(), b.getId()) or Comparator.comparingInt(X::getId). Because the broken comparator is also inconsistent, TimSort can throw IllegalArgumentException: Comparison method violates its general contract, and the same bug appears when long IDs are subtracted and cast to int.
What to remember
In this answer, we saw that a subtraction comparator returns the wrong sign when the true difference leaves the int range, which needs IDs far apart with different signs, such as 2,000,000,000 and -1,000,000,000. The broken comparator is also inconsistent, so TimSort may throw Comparison method violates its general contract and sorted collections misplace entries. Integer.compare or Comparator.comparingInt fixes it, and Long.compare or comparingLong fixes the cast-to-int version for long IDs.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
a.getId() - b.getId() overflows when the two IDs are far apart with different signs: for example 2,000,000,000 minus -1,000,000,000 is 3,000,000,000, which does not fit in an int and wraps to a negative number, so the comparator says the larger ID is smaller. Use Integer.compare(a.getId(), b.getId()) or Comparator.comparingInt(X::getId). Because the broken comparator is also inconsistent, TimSort can throw IllegalArgumentException: Comparison method violates its general contract, and the same bug appears when long IDs are subtracted and cast to int.
Why this question is asked
The subtraction comparator is an old idiom. It looks clever, it is shorter than an if statement, and it works in every test with small numbers, which is exactly why it survives until production data includes large or negative values. Interviewers ask about it because the bug is invisible unless we think about how int arithmetic behaves at its limits. In this answer, we will recap what a comparator must return, see exactly how the subtraction overflows with real numbers, see why the sort can even crash, and then fix it for int and long IDs.
1A Quick Recap of What compare Must Return
A comparator's compare(a, b) must return a negative number when a should come before b, zero when they are equal in the order, and a positive number when a should come after b. Only the sign matters, which is what makes subtraction tempting: if a is 7 and b is 3, a - b is 4, positive, so a comes after b.
An int in Java is 32 bits and holds values from -2,147,483,648 to 2,147,483,647. Arithmetic that goes past those limits does not fail; it wraps around silently. Adding 1 to the maximum gives the minimum. That silent wrap is the whole bug.
2Watching the Subtraction Overflow
Let us try the comparator on a pair of IDs that are far apart and have different signs.
| a | b | a - b as int | Correct sign |
|---|---|---|---|
| 7 | 3 | 4 (positive) | positive: correct |
| 2000000000 | -1000000000 | -1294967296 (negative) | positive: wrong |
| -2147483648 | 1 | 2147483647 (positive) | negative: wrong |
| 100 | 100 | 0 | zero: correct |
The true difference, three billion, is larger than the maximum int, so it wraps around to a negative number and the comparator returns the wrong sign. Notice that the problem needs values far apart. If all IDs are non-negative, the difference of any two of them always fits in an int, so the subtraction happens to be safe. That is why tests with ordinary sequential IDs pass: the failure needs negative IDs, such as hash-based identifiers, values from an external system, offsets or sentinel values like Integer.MIN_VALUE.
3Why the Sort Can Throw an Exception
A wrong sign for one pair is bad enough, but it also makes the comparator inconsistent. A comparator must be transitive: if a comes before b and b before c, then a must come before c. With overflow, we can have three IDs where each one appears to come before the next in a circle, which no order can satisfy.
Java's object sort, TimSort, used by List.sort, Collections.sort and Arrays.sort for objects, checks some of its assumptions while merging runs. When it notices that the comparator has contradicted itself, it throws java.lang.IllegalArgumentException: Comparison method violates its general contract!. It does not detect every inconsistency, so the same bug may produce a silently wrong order on one input and an exception on another, which is why it looks intermittent. Sorted collections such as TreeMap do not throw at all; they just misplace entries, so lookups can fail.
4The Fix: Integer.compare or comparingInt
Integer.compare returns the correct sign for any two ints, because it compares them instead of subtracting. Comparator.comparingInt builds a comparator that uses it.
Both are as fast as the subtraction in practice, so there is no performance reason to keep the old idiom. The same applies to compareTo methods: return Integer.compare(id, other.id), never id - other.id. For descending order, use Comparator.comparingInt(Item::getId).reversed() or swap the arguments to Integer.compare; never negate a subtraction, which overflows in the same way.
5The Same Bug With long IDs Cast to int
With long IDs, a compareTo must still return an int, and a common shortcut is to subtract the longs and cast the result. The cast keeps only the low 32 bits, which can change the sign or turn a real difference into zero.
This version can be even worse than the int one, because a result of zero tells a TreeSet or TreeMap that the two elements are the same, so one of them is silently dropped. Long.compare and comparingLong are the fix, and the same reasoning applies to double keys, where Double.compare also handles NaN and negative zero consistently.
6Follow-up questions
Is subtraction ever safe in a comparator?
It is safe when the range of values guarantees the difference fits, for example for byte, short or char values promoted to int, or for ints known to be non-negative. But that guarantee is usually implicit and breaks when the data changes, so using the compare methods everywhere is simpler and costs nothing.
Why does TimSort throw only sometimes?
TimSort only notices an inconsistency when its merging logic reaches a state that a consistent comparator could never produce. That depends on the input order and size; small arrays are sorted with insertion sort, which does not perform those checks. So the exception appears only for some inputs, typically larger ones.
Would static analysis catch this?
Often, yes. Tools such as SpotBugs and Error Prone have rules that flag comparators and compareTo methods implemented by subtraction, and IntelliJ IDEA has an inspection for it. Enabling such rules is cheap insurance.
7Conclusion
In this answer, we saw that a subtraction comparator returns the wrong sign when the true difference leaves the int range, which needs IDs far apart with different signs, such as 2,000,000,000 and -1,000,000,000. The broken comparator is also inconsistent, so TimSort may throw Comparison method violates its general contract and sorted collections misplace entries. Integer.compare or Comparator.comparingInt fixes it, and Long.compare or comparingLong fixes the cast-to-int version for long IDs.
Open with
The subtraction looks like it gives the right sign, but int arithmetic wraps around on overflow. If the IDs are far apart with different signs, say two billion and minus one billion, the true difference is three billion, which does not fit in an int, so it wraps to a negative number and the comparator says the bigger ID comes first.
Then, if they want more
With non-negative IDs it happens to be safe, which is why tests pass and production with negative or external IDs does not.
It also makes the comparator inconsistent, so you can get a cycle where a is before b, b before c and c before a, and TimSort, which checks some of these assumptions while merging, may throw IllegalArgumentException: Comparison method violates its general contract. That only shows up for some inputs, so it looks intermittent.
The fix is Integer.compare(a.getId(), b.getId()), or better Comparator.comparingInt(Item::getId), which is just as fast. The same bug exists for long IDs when people subtract and cast to int: the cast keeps only the low 32 bits, so the sign can flip or two different IDs can compare as equal and one gets dropped from a TreeSet. There I use Long.compare or comparingLong.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A comparator is written as (a, b) -> a.getId() - b.getId() for int IDs. Sorting...": https://scrivio-interview-library.netlify.app/java/object-contracts/b073d970e4/