Long,Integer和Short的比较方法的不同实现?

flu*_*y03 9 java integer compare short long-integer

为什么静态方法的实现compareLong,IntegerShort在Java中的图书馆有什么不同?

用于Long:

public static int compare(long x, long y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Run Code Online (Sandbox Code Playgroud)

用于Integer:

public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Run Code Online (Sandbox Code Playgroud)

用于Short:

public static int compare(short x, short y) {
    return x - y;
}
Run Code Online (Sandbox Code Playgroud)

孙兴斌*_*孙兴斌 15

如果你试试:

System.out.println(Long.MIN_VALUE - Long.MAX_VALUE);
Run Code Online (Sandbox Code Playgroud)

要么

System.out.println(Integer.MIN_VALUE - Integer.MAX_VALUE);
Run Code Online (Sandbox Code Playgroud)

你会1因为溢出而得到(更新:这里应该是下溢,如另一个答案所述),这是不正确的.

然而,随着

System.out.println(Short.MIN_VALUE - Short.MAX_VALUE);
Run Code Online (Sandbox Code Playgroud)

您将获得正确的值-65535,因为shortint-操作之前转换为,这可以防止溢出.