Video in progress

Strong Middle 🧠 Problem solving

What is wrong with this comparator, and when does it show up?

list.sort((a, b) -> a.getBalance() - b.getBalance()); // getBalance() returns an int

Subtracting a - b overflows the int range on large numbers and flips the sign. The order comes out wrong, and TimSort sometimes throws "Comparison method violates its general contract!". The right way is Integer.compare(a, b).

📖 Answer

Integer.MAX_VALUE - (-1) overflows and gives a negative number. In other words, the comparator says "the bigger number is smaller". With small numbers the test passes, and the bug appears only on prod, when boundary values show up.

int a = 2_000_000_000, b = -2_000_000_000;
System.out.println(a - b);                 // -294967296 — negative!
System.out.println(Integer.compare(a, b)); // 1

The comparator stops being transitive: a < b, b < c, but c < a. Since Java 7, Collections.sort and Arrays.sort for objects use TimSort. In some checks it notices this contradiction and throws IllegalArgumentException: Comparison method violates its general contract!. If it doesn't notice, it just sorts wrongly. Both are unpleasant.

The right way to write it:

list.sort(Comparator.comparingInt(Account::getBalance));
// or
list.sort((a, b) -> Integer.compare(a.getBalance(), b.getBalance()));

Similar traps:

  • (int)(a.getId() - b.getId()) for a long: overflow and truncation together;
  • subtracting doubles and casting to (int): the difference between 0.3 and 0.1 becomes 0, so they're treated as "equal";
  • if compare and equals don't agree, a TreeSet drops an "equal" element.

To catch this kind of bug, a property-based test (jqwik) works well: it checks transitivity with random inputs, including boundary ints.