Why are Byte.compare() and Integer.compare() implemented differently?
Asked Answered
G

2

39

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?

Geneviegenevieve answered 12/11, 2013 at 8:16 Comment(5)
@Discipol your statement is correct, but that's not the reason in that case! ;)Auburta
Hey, that Integer comparision never returns positive numbers, is that just a typo in + - 1 ?Treacle
there seems to be an error in the snippet you pasted: it should be return (x < y) ? -1 : ((x == y) ? 0 : 1);Phoebe
Above implementation of int compare() doesn't return +ve value ever. Is it correct?Ringleader
You are right. I modified question. Sorry, I made a mistake.Geneviegenevieve
A
49

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)

Auburta answered 12/11, 2013 at 8:20 Comment(0)
T
8

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

Tosh answered 12/11, 2013 at 8:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.