加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java的平等运算符是可交换的吗?

发布时间:2020-12-15 03:12:09 所属栏目:Java 来源:网络整理
导读:请考虑以下 Java代码: Integer foo = bar();if(foo == 5) ...;if(5 == foo) ...; 这些比较是否相等 – 尤其是foo为空的可能性?它们是扩展为foo.getValue()== 5和5 == foo.getValue(),还是更类似于foo.equals(new Integer(5))和new Integer(5).equals(foo),
请考虑以下 Java代码:
Integer foo = bar();
if(foo == 5) ...;
if(5 == foo) ...;

这些比较是否相等 – 尤其是foo为空的可能性?它们是扩展为foo.getValue()== 5和5 == foo.getValue(),还是更类似于foo.equals(new Integer(5))和new Integer(5).equals(foo),还是别的什么? NPM中可能有一个或两个或两个都没有?

解决方法

从 JLS:

15.21.1. Numerical Equality Operators == and !=

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).

5.1.8的相关规则是:

If r is a reference of type Integer,then unboxing conversion converts
r into r.intValue()

5.6.2说:

5.6.2. Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of
operands,each of which must denote a value that is convertible to a
numeric type,the following rules apply,in order:

If any operand is of a reference type,it is subjected to unboxing
conversion (§5.1.8).

这意味着if(foo == 5)…;表示与if(foo.intValue()== 5)…相同; if(5 == foo)表示if(5 == foo.intValue()).如果foo等于null,那么无论哪种情况都会得到一个NPE.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读