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

时间:2018-03-03 13:20:33

标签: java integer compare long-integer short

为什么Java库中compareLongInteger的静态方法Short的实现不同?

Long

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

Integer

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

Short

public static int compare(short x, short y) {
    return x - y;
}

3 个答案:

答案 0 :(得分:15)

如果您尝试:

System.out.println(Long.MIN_VALUE - Long.MAX_VALUE);

System.out.println(Integer.MIN_VALUE - Integer.MAX_VALUE);

由于溢出,您将获得1(更新:此处应该是下溢,如另一个答案所述),这是不正确的。

然而,

System.out.println(Short.MIN_VALUE - Short.MAX_VALUE);

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

答案 1 :(得分:4)

x - y可能是最有效的(因为替代方案涉及分支两次),因此用于short

x - y无法用于intlong,因为当结果值不适合{int时,overflow {1}},当结果为负时可以给出正值,或者当结果为正时给出负值(或者在任何一种情况下为零)。

注意:减去两个shortthe resulting value is of type int时,永远不会溢出。

// 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

对于它的价值:选择上面的值,因为它们大致围绕int(和short)的最小值和最大值,以证明此时的值它溢出了。

答案 2 :(得分:2)

int的值可以在[-2147483648, +2147483647]之间。如果您从-2147483648中减去+2147483647,则会获得4294967295。这不能存储在int中,因此我们使用它来比较2个整数

return (x < y) ? -1 : ((x == y) ? 0 : 1);

长期也是如此。