Card 06/ 09
All 9 cards
GotchaDifficulty: Advanced1 min
Why Subtracting Two ints in a Comparator Is a Bug
A comparator that has sorted correctly for years produces one wrong ordering on a dataset with a very large value and a very negative one in it.
(a, b) -> a.score() - b.score()The trick relies on the sign of the difference, and subtraction of two int values can overflow. Two billion minus negative two billion is four billion, which does not fit in an int, so the result wraps round and comes out negative — which the sort reads as "the first one is smaller".
int big = 2_000_000_000;
int verySmall = -2_000_000_000;
System.out.println(big - verySmall);-294967296Two billion is the larger score, so a correct comparator returns something positive. This one returns a negative number, so the sort puts the larger score first — and a sort given inconsistent answers produces an order that is wrong in ways that are very hard to reproduce.
Use Integer.compare(a, b), or Comparator.comparingInt(...), both of which compare rather than subtract. The same applies to long, where the wrap-around is rarer and just as fatal.