Java hashMap NullPointerException [重复]

问题描述 投票:-3回答:1

这个问题在这里已有答案:

我有两个hashMaps:

private HashMap<String, HashMap<String, Integer>> attributesCountPerCategory;

private HashMap<String, Integer> attributesCount;

我也有方法:

public void increaseAttributes(String attr, String category){
    HashMap<String, Integer> attributes = this.attributesCountPerCategory.get(category);
    if (attributes == null) {
        this.attributesCountPerCategory.put(category, new HashMap<String, Integer>());
        attributes = this.attributesCountPerCategory.get(category);
    }

    Integer c = attributes.get(attr);
    if(c == null){
        attributes.put(attr, 0);
        c = attributes.get(attr);
    }
    attributes.put(attr,c++);

    Integer c2 = this.attributesCount.get(attr);
    if(c2 == null){
        this.attributesCount.put(attr,0);
        c2 = this.attributesCount.get(attr);            
    }
    this.attributesCount.put(attr,c2++);        
}

因此,当我调用此方法时,即使我在对象引用中检查NullPointerException值,也会抛出null。在以下行中抛出异常:

HashMap<String, Integer> attributes = this.attributesCountPerCategory.get(category);

可能是什么问题呢?

java nullpointerexception
1个回答
1
投票

这是因为在这一行

HashMap<String, Integer> attributes = this.attributesCountPerCategory.get(category);

attributesCountPerCategory尚未初始化。这就是它为空的原因。

修复要么做

private HashMap<String, HashMap<String, Integer>> attributesCountPerCategory = new HaspMap<String, HashMap<String, Integer>> ();

或者在调用它之前在其他位置初始化它

© www.soinside.com 2019 - 2024. All rights reserved.