why does this code throw a NullPointerException?

后端 未结 2 1050
不思量自难忘°
不思量自难忘° 2021-01-18 10:41

Eventually I got the answer, but it puzzled me for a while.

Why does the following code throws NullPointerException when run?

import java.util.*;

c         


        
相关标签:
2条回答
  • 2021-01-18 11:06

    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.

    This is specified in JLS 5.1.8:

    5.1.8 Unboxing Conversion

    At run time, unboxing conversion proceeds as follows:

    • If r is null, unboxing conversion throws a NullPointerException

    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++);
    

    It's a bit more readable :)

    0 讨论(0)
  • 2021-01-18 11:21

    You are assigning int p to the return value of m.put(). But put() returns null in this situation, and you can't assign an int to null.

    From the Javadocs for HashMap.put():

    Returns: previous value associated with specified key, or null if there was no mapping for key.

    0 讨论(0)
提交回复
热议问题