为什么这段代码会抛出NullPointerException?

Osc*_*Ryz 6 java 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
    }
}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 11

因为在您尝试将其分配时m.put返回null(表示没有"之前"值)int.替换int pInteger p,它将工作.

这在JLS 5.1.8中指定:

5.1.8拆箱转换

在运行时,取消装箱转换过程如下:

  • 如果[Rnull,拆箱转换抛出一个NullPointerException

与问题无关,只考虑DRY的一个侧面建议,考虑这样写:

    Integer p = m.put("oscar", a == null ? 1 : a++);
Run Code Online (Sandbox Code Playgroud)

它更具可读性:)


Jus*_*ini 5

您正在分配int p给的返回值m.put().但是在这种情况下put()返回null,你无法分配intnull.

来自Javadocs HashMap.put():

返回: 与指定键关联的上一个值,如果没有键映射,则返回 null.