The subtraction "trick" to compare two numerical value is broken!!!
int a = -2000000000;
int b = 2000000000;
System.out.println(a - b);
// prints "294967296"
Here, a < b
, yet a - b
is positive.
DO NOT use this idiom. It doesn't work.
Moreover, even if it does work, it will NOT provide any significant improvement in performance, and may in fact cost readability.
See also
- Java Puzzlers Puzzle 65: A Strange Saga of Suspicious Sort
This puzzle has several lessons. The most specific is: Do not use a subtraction-based comparator unless you are sure that the difference between values will never be greater than Integer.MAX_VALUE
. More generally, beware of int
overflow. Another lesson is that you should avoid "clever" code. Strive to write clear, correct code, and do not optimize it unless it proves necessary.
Integer.compare(thisVal, anotherVal)
instead of writing out the ternary expression. – Burke