HashMap的get()方法的NullPointerException
@author:Jingdai
@date:2020.12.07
今天写代码发现一个 bug,HashMap的 get() 方法一直报空指针异常,现记录一下。
看下面代码。
private HashMap<Integer, Integer> cache;
private LinkedList<Integer> keyList;
private int capacity;
public LRUCache(int capacity) {
cache = new HashMap<>();
keyList = new LinkedList<>();
this.capacity = capacity;
}
// Put it in the front if use
public int get(int key) {
keyList.remove(new Integer(key));
keyList.addFirst(key);
return cache.get(key);
}
最后一行的 cache.get(key)
一直报 NullPointerException
。首先,LRUCache
对象我是 new
出来的,在构造函数会对 cache
进行初始化,不会是 null
,debug 中也验证了,cache
不是 null
。
接着去查看 Java API,如下:
V get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
Java API 明确说明当给定的 key 不存在时,会返回 null
,不会抛出 NullPointerException
。
说明不是这里的问题,那既然会返回 null
,好像懂了,如果 key 值不存在,当返回 null 时,如果用基本数据类型接收结果,如下面的代码。
public static void main(String[] args) {
HashMap<Integer, Integer> map = new HashMap<>();
int i = map.get(5);
}
这就会将 null
赋给 i
,这里会有一个自动拆箱过程,会调用返回值的 intValue()
方法并将结果赋值给 i
,但是这个返回值是 null
,那么 null.intValue()
便会出现 NullPointerException
。最开始的 return cache.get(key);
也是一样,返回值是 null
,但是函数类型是 int,在转换时也出现了 NullPointerException
。
所以虽然 HashMap
的 get()
方法不会出现 NullPointerException
,但是在包装类和基本类型转换时还是可能会出现 NullPointerException
,编程时需要注意。