Java Integer compareTo() - 为什么使用比较与减法? [英] Java Integer compareTo() - why use comparison vs. subtraction?

查看:37
本文介绍了Java Integer compareTo() - 为什么使用比较与减法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

推荐答案

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆