[英]why does this code throw a NullPointerException?
最终我得到了答案,但它让我困惑了一段时间。
为什么以下代码在运行时抛出NullPointerException?
import java.util.*;
class WhyNullPointerException {
public static void main( String [] args ){
// Create a map
Map<String,Integer> m = new HashMap<String,Integer>();
// Get the previous value, obviously null.
Integer a = m.get( "oscar" );
// If a is null put 1, else increase a
int p = a == null ?
m.put( "oscar", 1) :
m.put( "oscar", a++ ); // Stacktrace reports Npe in this line
}
}
因为当你尝试将它分配给int
m.put
返回null
(表示没有“previous”值)。 用Integer p
替换int p
它会起作用。
这在JLS 5.1.8中指定:
5.1.8拆箱转换
在运行时,取消装箱转换过程如下:
- 如果r为
null
,则取消装箱转换会抛出NullPointerException
与问题无关,只考虑DRY的一个侧面建议,考虑这样写:
Integer p = m.put("oscar", a == null ? 1 : a++);
它更具可读性:)
您将int p
赋值给m.put()
的返回值。 但是put()
在这种情况下返回null
,并且你不能将int
赋值为null
。
从Javadocs for HashMap.put()
:
返回:与指定键关联的上一个值,如果没有键映射,则返回 null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.