三元条件表达式中出现奇怪的 NullPointerException
Strange NullPointerException in ternary conditional expression
谁能告诉我为什么 Java 会在此处抛出 NullPointerException
?
Float x = <some condition> ? myObject.getSomeFloat() : 0.0f;
- 方法
getSomeFloat
returnsFloat
.
- 将
0.0f
更改为 new Float(0)
效果很好。
这个三元运算符的类型是float
。因此,如果 myObject.getSomeFloat()
returns null,当 <some condition>
为真时抛出 NullPointerException
并调用 myObject.getSomeFloat().floatValue()
以将 Float
转换为float
.
If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.
在您的例子中,您有一个原始类型 - 浮点型 - 以及该浮点型的盒装版本 - 浮点型。因此,条件表达式的类型是原始类型——float。
谁能告诉我为什么 Java 会在此处抛出 NullPointerException
?
Float x = <some condition> ? myObject.getSomeFloat() : 0.0f;
- 方法
getSomeFloat
returnsFloat
. - 将
0.0f
更改为new Float(0)
效果很好。
这个三元运算符的类型是float
。因此,如果 myObject.getSomeFloat()
returns null,当 <some condition>
为真时抛出 NullPointerException
并调用 myObject.getSomeFloat().floatValue()
以将 Float
转换为float
.
If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.
在您的例子中,您有一个原始类型 - 浮点型 - 以及该浮点型的盒装版本 - 浮点型。因此,条件表达式的类型是原始类型——float。