Why are Byte.compare() and Integer.compare() implemented differently?
The implementation of Integer.compare
does not use subtraction, as this could cause an overflow in case you're comparing an integer that is close to Integer.MIN_VALUE
with another that is close to Integer.MAX_VALUE
.
This overflow cannot happen in case of Byte.compare
, as there the byte values are implicitely converted to integers before x-y
is calculated.
(see also: Java Language Specification - 5.6.2 Binary Numeric Promotion)