小编典典
如果您的代码不能保证incomingDictionary会在到达此方法之前将其初始化,则您将必须执行null检查,没有出路
public void addDictionary(HashMap incomingDictionary) {
if (incomingDictionary == null) {
return; // or throw runtime exception
}
if (totalDictionary == null) {
return;// or throw runtime exception
}
if (totalDictionary.isEmpty()) {
totalDictionary.putAll(incomingDictionary);
} else {
for (Entry incomingIter : incomingDictionary.entrySet()) {
String incomingKey = incomingIter.getKey();
Integer incomingValue = incomingIter.getValue();
Integer totalValue = totalDictionary.get(incomingKey);
// If total dictionary contains null for the incoming key it is
// as good as replacing it with incoming value.
Integer sum = (totalValue == null ?
incomingValue : incomingValue == null ?
totalValue : totalValue + incomingValue
);
totalDictionary.put(incomingKey, sum);
}
}
}
考虑到HashMap允许将null作为值在代码中容易发生NPE的另一个位置是
Integer newValue = incomingDictionary.get(key) + totalDictionary.get(key);
如果这两个都不为空,则将获得NPE。
2020-11-30