Java Zero to All All questionsPractise free
Interview questions › Core & Modern Java (8 -> 21) › Collections & Equals/HashCode Contracts

Why is implementing compareTo as a.value - b.value a bug, and what should you do instead?

Level III · MidCollections & Equals/HashCode Contracts
Short answer

Subtraction overflows for large or negative int values, so a comparison like a.value - b.value can return a positive number when a is actually smaller, silently corrupting sort order and breaking TreeMap and TreeSet invariants.

Explanation

The correct approach is Integer.compare(a.value, b.value), or for multiple fields Comparator.comparingInt(...).thenComparing(...). The same overflow trap is why you never hand-roll subtraction comparators; the built-in compare methods and Comparator combinators are safe and clearer.

Common mistakes
  • Using subtraction in compareTo, which overflows for large values.
  • Not using Integer.compare or Comparator.comparing.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Collections & Equals/HashCode Contracts.

Practise free

More on Collections & Equals/HashCode Contracts