HashMap的get()方法的NullPointerException
今天寫代碼發現一個 bug,HashMap的 get() 方法一直報空指針異常,現記錄一下。
看下面代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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 時,如果用基本數據類型接收結果,如下面的代碼。
1
2
3
4
|
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 ,編程時需要注意。
NullPointerException的一種情況
很久以前剛開始寫代碼的時候經常會從一些模板或者map、list或者一些對象里面取值
取到的值很可能是Object或某種類型 如果需要存儲轉化成String類型
我們會在后面加一個.toString()方法來強轉
1
2
|
Map<String,Object> map = Maps.newHashMap(); String userName = map.get( "username" ).toString(); |
如果我們取到了一個空值很可能會報空指針異常
我們可以嘗試String mius = "";
1
|
String userName = map.get( "username" )+mius; |
這樣就不會報錯了~
好久之前的小問題 分享一下 如有不足請補充,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_41512783/article/details/110819487