简体   繁体   English

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

[英]why does this code throw a NullPointerException?

Eventually I got the answer, but it puzzled me for a while. 最终我得到了答案,但它让我困惑了一段时间。

Why does the following code throws NullPointerException when run? 为什么以下代码在运行时抛出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
    }
}

Because m.put returns null (which indicates that there's no "previous" value) while you're trying to assign it to int . 因为当你尝试将它分配给int m.put返回null (表示没有“previous”值)。 Replace int p by Integer p and it will work. Integer p替换int p它会起作用。

This is specified in JLS 5.1.8 : 这在JLS 5.1.8中指定:

5.1.8 Unboxing Conversion 5.1.8拆箱转换

At run time, unboxing conversion proceeds as follows: 在运行时,取消装箱转换过程如下:

  • If r is null , unboxing conversion throws a NullPointerException 如果rnull ,则取消装箱转换会抛出NullPointerException

Unrelated to the problem, just a side suggestion with DRY in mind, consider writing it so: 与问题无关,只考虑DRY的一个侧面建议,考虑这样写:

    Integer p = m.put("oscar", a == null ? 1 : a++);

It's a bit more readable :) 它更具可读性:)

You are assigning int p to the return value of m.put() . 您将int p赋值给m.put()的返回值。 But put() returns null in this situation, and you can't assign an int to null . 但是put()在这种情况下返回null ,并且你不能将int赋值为null

From the Javadocs for HashMap.put() : 从Javadocs for HashMap.put()

Returns: previous value associated with specified key, or null if there was no mapping for key. 返回:与指定键关联的上一个值,如果没有键映射,则返回 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM