有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

添加到HashMap时出现java NullPointerException

在向HashMap添加数据时,我遇到了NullPointerException。我正在写一个类来计算特定物体的给定频率。以下是我的代码(去掉任何不必要的细节):

public class FrequencyCounter {

    private Map<Object, Integer> freq;

    public FrequencyCounter() {
        freq = new HashMap<Object, Integer>();
    }

    public int add(Object key) {        
        System.out.println("Map is null: " + (freq == null));
        System.out.println("Key is null: " + (key == null));
        if (freq.containsKey(key)) {
            return freq.put(key, freq.get(key) + 1);
        }
        return freq.put(key, 1);
    }

    public static void main(String[] args) {
        FrequencyCounter fc = new FrequencyCounter();
        fc.add(new Object());
    }
}

NPE发生在return freq.put(key, 1);行上。两个println语句都打印为false

你们知道我做错了什么吗


共 (2) 个答案

  1. # 1 楼答案

    这是因为HashMap.put(key, value)将返回与key关联的前一个值,或null。 在代码中,不能将freq.put(key,1)返回为int,因为它为null

  2. # 2 楼答案

    由于put()可能返回null,因此必须将返回类型更改为Integer,该类型可以为null:

    public Integer add(Object key) {        
        System.out.println("Map is null: " + (freq == null));
        System.out.println("Key is null: " + (key == null));
        if (freq.containsKey(key)) {
            return freq.put(key, freq.get(key) + 1);
        }
        return freq.put(key, 1);
    }
    

    并且在使用它之前必须验证null的返回值