I have two Hashmaps
HashMap<Integer, Integer> inventoryRequirements = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> inventory = new HashMap<Integer, Integer>();
I have a loop that checks current and adds to it:
for(Item item : items){
int currentRequirement = 0;
currentRequirement = inventoryRequirements.get(item.get_id());
inventoryRequirements.put(item.get_id(), currentRequirement++);
}
I have another loop that checks inventory and adds to it:
for(Item item : items){
int currentInventory = 0;
// this next line returns null
currentInventory = inventory.get(item.get_id());
inventory.put(item.get_id(), currentInventory++);
}
The first one works fine, but the second one pukes and returns a null. I don't understand why the second one does not work. Both are initially in the same state as depicted in the code sample.
EDIT
The two HM get populated as you see here - really! I know it may be hard to believe but the first one works and the second one does not.
Returns null if the HashMap contains no mapping for this key. A return value of null does not necessarily indicate that the HashMap contains no mapping for the key; it's also possible that the HashMap explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.
Indeed, if a Java Map implementation allows for null values, then it is possible for the Map to return its value for the given key, but that value might be a null. Often this doesn't matter, but if it does, one can use Map. containsKey() to determine if the Map entry has a key entry.
Return Value: The method returns boolean true if the map is empty or does not contain any mapping pairs else boolean false.
HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Both of the loops you show will throw a NullPointerException
(NPE) if the key you request via get()
is not in the Map
.
Map.get()
returns null
when the key is not present (or of course if the value stored with that key is null
). An Integer
(autoboxed type) that is null
can not be autounboxed into an int
so it throws an NPE.
The safe way of performing this is:
for (Item item : items) {
Integer currentRequirement = inventoryRequirements.get(item.get_id());
if (currentRequirement != null) {
inventoryRequirements.put(item.get_id(), currentRequirement++);
}
}
Of course, it's also completely possible that you have an Item
in your collection that is null
and that is what is throwing the NPE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With