Java Integer compareTo() - 为什么使用比较与减法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2728793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:33:29  来源:igfitidea点击:

Java Integer compareTo() - why use comparison vs. subtraction?

javaoptimizationintegercomparisoninteger-overflow

提问by Vladimir

I've found that java.lang.Integerimplementation of compareTomethod looks as follows:

我发现方法的java.lang.Integer实现compareTo如下所示:

public int compareTo(Integer anotherInteger) {
    int thisVal = this.value;
    int anotherVal = anotherInteger.value;
    return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}

The question is why use comparison instead of subtraction:

问题是为什么使用比较而不是减法:

return thisVal - anotherVal;

回答by Itay Maman

This is due to integer overflow. When thisValis very large and anotherValis negative then subtracting the latter from the former yields a result that is bigger than thisValwhich may overflow to the negative range.

这是由于整数溢出。当thisVal非常大并且anotherVal为负时,则从前者中减去后者会产生大于thisVal可能溢出到负范围的结果。

回答by polygenelubricants

The subtraction "trick" to compare two numerical value is broken!!!

比较两个数值的减法“技巧”被破解了!!!

        int a = -2000000000;
        int b =  2000000000;
        System.out.println(a - b);
        // prints "294967296"

Here, a < b, yet a - bis positive.

这里,a < ba - b是正的。

DO NOT use this idiom. It doesn't work.

不要使用这个习语。它不起作用。

Moreover, even if it does work, it will NOTprovide any significant improvement in performance, and may in fact cost readability.

此外,即使它确实有效,它也不会提供任何显着的性能改进,并且实际上可能会降低可读性。

See also

也可以看看

  • Java PuzzlersPuzzle 65: A Strange Saga of Suspicious Sort

    This puzzle has several lessons. The most specific is: Do not use a subtraction-based comparator unless you are sure that the difference between values will never be greater thanInteger.MAX_VALUE. More generally, beware of intoverflow. Another lesson is that you should avoid "clever" code. Strive to write clear, correct code, and do not optimize it unless it proves necessary.

  • Java PuzzlersPuzzle 65: A Strange Saga of Suspicious Sort

    这个谜题有几个教训。最具体的是:不要使用基于减法的比较器,除非您确定值之间的差异永远不会大于Integer.MAX_VALUE。更一般地说,要注意int溢出。另一个教训是你应该避免“聪明”的代码。努力编写清晰、正确的代码,除非证明有必要,否则不要对其进行优化。

回答by fredoverflow

Simply speaking, the inttype is not big enough to store the difference between two arbitrary intvalues. For example, the difference between 1.5 billion and -1.5 billion is 3.0 billion, but intcannot hold values greater than 2.1 billion.

简单来说,int类型不足以存储两个任意int值之间的差异。例如,15 亿和-15 亿之间的差值是 30 亿,但int不能容纳大于 21 亿的值。

回答by Adamski

Perhaps it's to avoid overflow / underflow.

也许是为了避免上溢/下溢。

回答by PauliL

In addition to the overflow thing, you should note that the version with substraction does not give the same results.

除了溢出的东西,你应该注意带减法的版本不会给出相同的结果

  • The first compareTo version returns one of three possible values: -1, 0, or 1.
  • If you replace the last line with substraction, the result can be any integer value.
  • 第一个 compareTo 版本返回三个可能值之一:-1、0 或 1。
  • 如果用减法替换最后一行,结果可以是任何整数值。

If you know there will be no overflow, you could use something like this:

如果你知道不会有溢出,你可以使用这样的东西:

public int compareTo(Integer anotherInteger) {
    return sign(this.value - anotherInteger.valuel);
}