【发布时间】:2011-02-13 07:14:12
【问题描述】:
我发现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;
【问题讨论】:
-
当我们急于担心微优化时,我们经常会遇到错误的代码。
-
从 JDK 7 开始,可以使用
Integer.compare(thisVal, anotherVal)而不是写出三元表达式。
标签: java optimization integer comparison integer-overflow