为什么这段代码会抛出 NullPointerException? [英] why does this code throw a NullPointerException?
本文介绍了为什么这段代码会抛出 NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最终我得到了答案,但它让我困惑了一段时间.
Eventually I got the answer, but it puzzled me for a while.
为什么下面的代码运行时会抛出NullPointerException?
Why does the following code throws NullPointerException when run?
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
}
}
推荐答案
因为 m.put
返回 null
(表示没有前一个"值)当您尝试将其分配给 int
时.将 int p
替换为 Integer p
就可以了.
Because m.put
returns null
(which indicates that there's no "previous" value) while you're trying to assign it to int
. Replace int p
by Integer p
and it will work.
这在 JLS 5.1.8 中有规定:
在运行时,拆箱转换过程如下:
5.1.8 Unboxing Conversion
At run time, unboxing conversion proceeds as follows:
- 如果 r 是
null
,拆箱转换会抛出一个NullPointerException
- If r is
null
, unboxing conversion throws aNullPointerException
与问题无关,只是考虑到 DRY 的附带建议,请考虑这么写:
Unrelated to the problem, just a side suggestion with DRY in mind, consider writing it so:
Integer p = m.put("oscar", a == null ? 1 : a++);
它的可读性更强:)
这篇关于为什么这段代码会抛出 NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文