fluency03 :
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;
}
xingbin :
If you try:
System.out.println(Long.MIN_VALUE - Long.MAX_VALUE);
or
System.out.println(Integer.MIN_VALUE - Integer.MAX_VALUE);
You will get 1
because of overflow(update: should be underflow here, as mentioned in another answer), which is incorrect.
However, with
System.out.println(Short.MIN_VALUE - Short.MAX_VALUE);
you will get correct value -65535
, because short
will be converted to int
before -
operation, which prevents the overflow.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=439706&siteId=1