根据原始值检查空包装器
Integer i = null;
if (i == 3)
为什么上面的第二行抛出一个 NullPointerException
,恕我直言,这只有一个含义,即包装对象 i
将被拆箱,这会产生异常,例如:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(null);
int x = list.get(0);
编辑:你可以吗向我提供某种格式的文档吗?
Integer i = null;
if (i == 3)
Why the second line above throws a NullPointerException
, IMHO, this has only one meaning which is Wrapper Object i
is to be unboxed which yields the Exception such as:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(null);
int x = list.get(0);
EDIT: Can you supply me with some format doc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它会抛出 NPE,因为编译器会为您执行以下“魔法”:
显然,当
i
为null
时,i.intValue()
会抛出 NPE。It throws NPE because compiler does the following "magic" for you:
Obviously
i.intValue()
throws NPE wheni
isnull
.当您尝试将包装数字与原始数字进行比较时,包装器会自动拆箱。如果此时包装器为 null,您将得到 NullPointerException。这是自动装箱系统的常见陷阱之一(另一个是如果在循环中对数字进行装箱/拆箱,性能会很差)
When you try to compare a wrapped number with a primitive one, the wrapper is automatically un-boxed. If at that moment, the wrapper is null, you get a NullPointerException. This is one of the common pitfalls of the autoboxing system (the other being poor performance if you box/unbox numbers in a loop)
将包装类视为持有者对象。类似于:
如果指针或对整个对象的引用为 null,则无法获取该值来执行任何装箱/拆箱操作。
当您说:
拆箱
自动发生在null
引用上,因此出现异常。Think of the wrapper class to be a holder object. Something like:
If the pointer or the reference to the whole object is
null
, you cant get to the value to do anyboxing/unboxing
operations.When you say:
The
unboxing
occurs automatically on anull
reference, hence the exception.如果它没有对 Integer 进行拆箱,您会得到奇怪的行为,例如
或
This prints
因为引用而不是值不同。
If it didn't unbox the Integer you would get strange behaviour like
or
This prints
because the references rather than the values are different.
这可以避免在比较之前检查 value 是否为 null。
以下页面提供了一个很好的包装器,以避免 NPE
http://www.javawiki.org/wiki/Avoid_NullPointerException_on_Primitive_Wrapper_Objects< /a>
This can be avoided checking whether value is null before comparing it.
Following page provides a nice wrapper to avoid to NPE
http://www.javawiki.org/wiki/Avoid_NullPointerException_on_Primitive_Wrapper_Objects