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),还是别的什么? 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.

相关文章

应用场景 C端用户提交工单、工单创建完成之后、会发布一条工...
线程类,设置有一个公共资源 package cn.org.chris.concurre...
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)
在Java中找到正数和负数数组元素的数量