代码之家  ›  专栏  ›  技术社区  ›  OscarRyz

为什么此代码引发NullPointerException?

  •  6
  • OscarRyz  · 技术社区  · 15 年前

    最终我得到了答案,但这让我困惑了一段时间。

    为什么以下代码在运行时引发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
        }
    }
    
    2 回复  |  直到 15 年前
        1
  •  11
  •   BalusC    15 年前

    因为 m.put 收益率 null (表示没有“上一个”值)尝试将其分配给 int . 替换 int p 通过 Integer p 它会起作用的。

    这在 JLS 5.1.8 :

    5.1.8 Unboxing Conversion

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

    • 如果 R 无效的 ,取消装箱转换引发 NullPointerException

    与问题无关,只是一个附带的建议 DRY 记住,考虑这样写:

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

    它的可读性更强:)

        2
  •  5
  •   Justin Ardini    15 年前

    您正在分配 int p 到的返回值 m.put() . 但是 put() 收益率 null 在这种情况下,不能指定 int 无效的 .

    来自Javadocs的 HashMap.put() :

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