【问题标题】:Different implementations of compare method for Long, Integer and Short?Long,Integer和Short的比较方法的不同实现?
【发布时间】:2018-08-11 13:55:56
【问题描述】:

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

对于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;
}

【问题讨论】:

  • 因为所有情况下的返回类型都是int
  • 因为x - y 更简单并且适用于short。当然,它可以像其他方法一样做很长的路,但更简单的方法也更快,所以它是一个更好的实现。 x - y 不适用于intlong,所以他们必须使用三元运算符的方式。

标签: java integer compare long-integer short


【解决方案1】:

如果你尝试:

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,这样可以防止溢出。

【讨论】:

    【解决方案2】:

    x - y 大概是最有效的(因为替代方案涉及两次分支),所以它用于short

    但是x - y 不能用于intlong,因为当结果值不适合int 时,这将overflow,它可以在结果时给出正值应该是负数,或者当结果应该是正数时是负值(或者在任何一种情况下都为零)。

    注意:两个shorts、the 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)的最小值和最大值附近,以证明它在哪个点溢出。

    【讨论】:

      【解决方案3】:

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

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

      long也是如此。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-28
        • 1970-01-01
        • 2013-01-21
        • 2018-11-04
        • 2011-10-11
        • 1970-01-01
        • 1970-01-01
        • 2019-12-12
        相关资源
        最近更新 更多