Why are the implementations of the static method compare
for Long
, Integer
and Short
in Java's library different?
For Long
:
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
For Integer
:
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
For Short
:
public static int compare(short x, short y) {
return x - y;
}
@WeishiZeng: Yes, absolutely. Both operands in a + 1 are int - so that addition happens in int arithmetic, then the conversion to long , then the comparison.
The compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y) -1: if (x < y)
To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).
Thus, if you add a short to an int, short is the narrower type, so a temporary int with the closest value to the short is created. This temporary int value is added to the other int operand, and results is an int.
x - y
is presumably the most efficient (since the alternative involves branching twice), so that's used for short
.
But x - y
can't be used for int
or long
, because this will overflow when the resulting value doesn't fit in an int
, which can give a positive value when the result should be negative, or a negative value when the result should be positive (or zero in either case).
Note: when subtracting two short
s, the resulting value is of type int
, so that can never overflow.
// long - long
System.out.println((int)(2147483649l - 1l)); // -2147483648, not 2147483648
// int - int
System.out.println(-2147483648 - 1); // 2147483647, not -2147483649
// int - int
System.out.println(1 - -2147483648); // -2147483647, not 2147483649
// short - short
short s1 = -32768, s2 = 1;
System.out.println(s1 - s2); // -32769, as desired
For what it's worth: the values above were chosen since they're roughly around the minimum and maximum values for int
(and short
), to demonstrate at which point it overflows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With