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

comparison, integer, integer-overflow, java, optimization

Solution

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.

Problem

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; ```

Original source