<分区>
谁能告诉我为什么 Java 会在此处抛出 NullPointerException
?
Float x = <some condition> ? myObject.getSomeFloat() : 0.0f;
- 方法
getSomeFloat
返回Float
。 - 将
0.0f
更改为new Float(0)
效果很好。
<分区>
谁能告诉我为什么 Java 会在此处抛出 NullPointerException
?
Float x = <some condition> ? myObject.getSomeFloat() : 0.0f;
getSomeFloat
返回 Float
。0.0f
更改为 new Float(0)
效果很好。最佳答案
这个三元运算符的类型是float
.因此,如果 myObject.getSomeFloat()
返回 null,一个 NullPointerException
当 <some condition>
时抛出是真的 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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27730895/