Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException in Hashmap's get method

Tags:

java

I have a NullPointerException on this line:

 int qty = mSelectedBottles.get(bottleID);

I've checked that mSelectedBottles and bottleID are both NOT null.

mSelectedBottles is of type Hashmap<Integer, Integer> and bottleID is of type int

like image 278
0xSina Avatar asked Mar 31 '14 07:03

0xSina


1 Answers

Because, Unboxing of a null value to primitive datatype. Here's enough code to recreate that NullPointerException yourself

int x;
HashMap<String,Integer> map = new HashMap<String,Integer>();
x = map.get("hello");

The auto-unboxing of the non-existent value was the issue.

We know autoboxing was introduced to make coding easier, but it's a definite performance anti-pattern and can lead to annoying bugs like this which are non-intuitive.

Personally, I always try to remove autoboxing by making any such calls explicit, so that although the code is a little uglier, it's also clearer what's happening.

You have to check mSelectedBottles.get(bottleID) is null or not before unboxing it to primitive int

From Java Performance News Letter

like image 150
Abimaran Kugathasan Avatar answered Sep 23 '22 22:09

Abimaran Kugathasan