I have a program that needs to merge two HashMap. The hashmaps have a key that is a String and a value that is an Integer. The special condition of the merge is that if the key is already in the dictionary, the Integer needs to be added to the existing value and not replace it. Here is the code I have so far that is throwing a NullPointerException.
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));
}
}
}
If your code cannot guarantee that
incomingDictionarywill be initialized before it reaches this method, you will have to do a null check, no way outConsidering HashMap allows null as value another place in your code which is prone to NPE is
if either of these two is null you will get NPE.