我发现 compareTo
方法的 java.lang.Integer
实现如下所示:
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
的结果,该结果可能会溢出到负范围。
关于Java Integer compareTo() - 为什么使用比较与减法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2728793/