Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different implementations of compare method for Long, Integer and Short?

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;
}
like image 888
fluency03 Avatar asked Mar 03 '18 13:03

fluency03


People also ask

Can you compare long and int?

@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.

How do you compare methods in Java?

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)

How do you compare integers in Java?

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).

Can we add short and int in Java?

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.


1 Answers

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 shorts, 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.

like image 151
Bernhard Barker Avatar answered Nov 04 '22 06:11

Bernhard Barker