javaoptimizationintegercomparisoninteger-overflow

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


I've found that java.lang.Integer implementation of compareTo method looks as follows:

public int compareTo(Integer anotherInteger) {
    int thisVal = this.value;
    int anotherVal = anotherInteger.value;
    return ( thisVal < anotherVal ? -1 : ( thisVal == anotherVal ? 0 : 1 ) ) ;
}

The question is why use comparison instead of subtraction:

return thisVal - anotherVal;

Solution

  • Integer overflow

    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.