Frage

I am studying the source of the OpenJDK.

My attention was attracted by the methods Byte.compare() and Integer.compare():

public static int Byte.compare(byte x, byte y) {
    return x-y;
}

public static int Integer.compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

Why do the methods Byte.compare() and Integer.compare() have different implementations?

War es hilfreich?

Lösung

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)

Andere Tipps

The Byte method can be implemented this way, becasue the result of the subtraction is representable in int. This is not so in the other case. For example:

0 - 0x80000000 == 0x80000000

and this is negative, hence the comparision would wrongly indicate that 0 is smaller than -2^31

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top