正确的整数java_如何正确比较两个整数在Java?

不,==在整数,长等之间将检查引用相等 – 即

Integer x = ...;

Integer y = ...;

System.out.println(x == y);

这将检查x和y是否指向相同的对象而不是等于对象。

所以

Integer x = new Integer(10);

Integer y = new Integer(10);

System.out.println(x == y);

保证打印为假。实现“小”自动装箱值可能会导致棘手的结果:

Integer x = 10;

Integer y = 10;

System.out.println(x == y);

这将打印为真,由于拳击规则(JLS section 5.1.7)。它仍然使用引用相等,但引用真的是相等的。

我个人会使用:

if (x.intValue() == y.intValue())

要么

if (x.equals(y))

后者效率稍低一些 – 对于Integer.equals(Integer)没有重载,所以它必须执行执行时类型检查,而第一个使用事实,我们已经知道两个对象都是整数。

幸运的是,compareTo知道类型,所以:

if (x.compareTo(y) < 0)

应该仍然有效。当然,这是微优化领域,你应该使用你找到最清晰的代码 – 确保它是正确的:)

正如你所说,对于包装器类型(整数,长等)和数字类型(int,long等)之间的任何比较,包装器类型值被取消装箱,并且测试被应用于所涉及的原始值。

这是二进制数字促销(JLS section 5.6.2)的一部分。查看每个运算符的文档以查看它是否应用。例如,从==和!=的文档(JLS 15.21.1):

If the operands of an equality

operator are both of numeric type, or

one is of numeric type and the other

is convertible (§5.1.8) to numeric

type, binary numeric promotion is

performed on the operands (§5.6.2).

和对于和> =(JLS 15.20.1)

The type of each of the operands of a

numerical comparison operator must be

a type that is convertible (§5.1.8) to

a primitive numeric type, or a

compile-time error occurs. Binary

numeric promotion is performed on the

operands (§5.6.2). If the promoted

type of the operands is int or long,

then signed integer comparison is

performed; if this promoted type is

float or double, then floating-point

comparison is performed.

请注意,如果这两种类型都不是数字类型,则不会将其视为这种情况的一部分。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值