我有一个程序需要合并两个HashMap
。 hashmaps的密钥是String
,值是Integer
。合并的特殊情况是,如果密钥已存在于字典中,则需要将Integer
添加到现有值中,而不是将其替换。这里是我到目前为止的代码投掷NullPointerException
。在Java中合并2个HashMaps
public void addDictionary(HashMap<String, Integer> incomingDictionary) {
for (String key : incomingDictionary.keySet()) {
if (totalDictionary.containsKey(key)) {
Integer newValue = incomingDictionary.get(key) + totalDictionary.get(key);
totalDictionary.put(key, newValue);
} else {
totalDictionary.put(key, incomingDictionary.get(key));
}
}
}
NPE被抛出的线是什么? – BenCole
你是否初始化了'totalDictionary'字段? – BenCole
totalDictionary已声明,但未初始化为包装此函数的类中较早的私有成员数据。 Eclipse显示在for循环处引发的异常。 – SmashCode