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

前端之家收集整理的这篇文章主要介绍了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.

猜你在找的Java相关文章