Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

compareto

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?

like image 510
Sergey Morozov Avatar asked Nov 12 '13 08:11

Sergey Morozov


Video Answer


2 Answers

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)

like image 138
isnot2bad Avatar answered Sep 24 '22 02:09

isnot2bad


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

like image 22
Ingo Avatar answered Sep 25 '22 02:09

Ingo