简体   繁体   中英

NullPointerException in Hashmap's get method

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM