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

标签 java optimization integer comparison integer-overflow

我发现 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/

相关文章:

hibernate - 如何避免 HQL 和 Criteria 中不必要的选择和连接

c - 具有定义宽度的整数类型

java - 类型不匹配 : cannot convert from DataProvider to Annotation

java - 在android上实现自动颜色(photoshop工具)

java - 哪种算法可以更快地检查某个位是否已设置?

swift - Swift 中的最大公共(public)指数

Java装箱和拆箱

java - 是什么导致了我的 java.net.SocketException : Connection reset?

java - Tapestry 组件缓存

mysql - SQL select语句优化(id,parent_id,child_ids)