Java Integer compareTo() - why use comparison vs. subtraction?

Perhaps it's to avoid overflow / underflow.


This is due to integer overflow. When thisVal is very large and anotherVal is negative then subtracting the latter from the former yields a result that is bigger than thisVal which may overflow to the negative range.


Simply speaking, the int type is not big enough to store the difference between two arbitrary int values. For example, the difference between 1.5 billion and -1.5 billion is 3.0 billion, but int cannot hold values greater than 2.1 billion.


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.