Java自动装箱/拆箱怪异
下面的代码产生一个 NPE:
Integer test = null;
Integer test2 = true ? test : 0;
System.out.println(test2);
要正确打印出“null”而没有异常,需要以下代码:
Integer test = null;
Integer test2 = true ? test : (Integer)0;
System.out.println(test2);
在第一个示例中很明显“test”正在被拆箱(转换为本机 int),但是为什么?为什么更改三元运算符中的其他表达式(如第二个示例中)可以修复它?谁能提供某种叙述,说明这两个示例中的内容何时、什么以及为何被装箱和拆箱?
Possible Duplicates:
Booleans, conditional operators and autoboxing
Java, Google Collections Library; problem with AbstractIterator?
The code below produces a NPE:
Integer test = null;
Integer test2 = true ? test : 0;
System.out.println(test2);
To correctly print out "null" without an exception requires this code:
Integer test = null;
Integer test2 = true ? test : (Integer)0;
System.out.println(test2);
It's obvious in the first example that "test" is being unboxed (converted to native int), but why? And why does changing the other expression in the ternary operator (as in the 2nd example) fix it? Can anyone provide some kind of narrative of exactly when, what, and why stuff in both of the examples gets boxed and unboxed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自Java 语言规范的第 15.25 节:
因此,它遵循最后一个要点,执行二进制数字提升,从而执行拆箱转换。因此,条件运算符表达式的类型为
int
,即使您将其分配给Integer
也是如此。它尝试对null
执行拆箱转换,因此出现异常。From section 15.25 of the Java Language Specification:
So it's following the final bullet, performing binary numeric promotion, which performs an unboxing conversion. So the type of the conditional operator expression is
int
, even though you're assigning it to anInteger
. It's trying to perform the unboxing conversion onnull
, hence the exception.