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中可能有一个或两个或两个都没有?
解决方法
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.