简体   繁体   English

Hashmap的get方法中的NullPointerException

[英]NullPointerException in Hashmap's get method

I have a NullPointerException on this line: 我在这一行有一个NullPointerException

 int qty = mSelectedBottles.get(bottleID);

I've checked that mSelectedBottles and bottleID are both NOT null. 我已经检查过mSelectedBottlesbottleID都是null。

mSelectedBottles is of type Hashmap<Integer, Integer> and bottleID is of type int mSelectedBottles的类型为Hashmap<Integer, Integer>bottleID的类型为int

Because, Unboxing of a null value to primitive datatype. 因为,将null值拆分为原始数据类型。 Here's enough code to recreate that NullPointerException yourself 这里有足够的代码来自己重新创建NullPointerException

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 在将其拆箱到原始int之前,您必须检查mSelectedBottles.get(bottleID)是否为null

From Java Performance News Letter 来自Java Performance News Letter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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