Java Integer compareTo() - 为什么使用比较和减法? [英] Java Integer compareTo() - why use comparison vs. subtraction?
本文介绍了Java Integer compareTo() - 为什么使用比较和减法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现 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));问题是为什么使用比较而不是减法: return thisVal - anotherVal;
解决方案当 thisVal
非常大且 anotherVal
为负值时,从前者减去后者得到大于 thisVal
,这可能会溢出到负值范围。
I've found that java.lang.Integer
implementation of compareTo
method looks as follows:
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;
解决方案 This is due to integer overflow. When thisVal
is very large and anotherVal
is negative then subtracting the latter from the former yields a result that is bigger than thisVal
which may overflow to the negative range.
这篇关于Java Integer compareTo() - 为什么使用比较和减法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文