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

Vladimir picture Vladimir · Apr 28, 2010 · Viewed 13.8k times · Source

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;

Answer

Itay Maman picture Itay Maman · Apr 28, 2010

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.