HashMap的get()方法的NullPointerException問題
HashMap的get()方法的NullPointerException
今天寫代碼發(fā)現(xiàn)一個 bug,HashMap的 get() 方法一直報空指針異常,現(xiàn)記錄一下。
看下面代碼
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 出來的,在構(gòu)造函數(shù)會對 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 時,如果用基本數(shù)據(jù)類型接收結(jié)果,如下面的代碼。
public static void main(String[] args) { HashMap<Integer, Integer> map = new HashMap<>(); int i = map.get(5); }
這就會將 null 賦給 i ,這里會有一個自動拆箱過程,會調(diào)用返回值的 intValue() 方法并將結(jié)果賦值給 i,但是這個返回值是 null,那么 null.intValue() 便會出現(xiàn) NullPointerException。
最開始的 return cache.get(key); 也是一樣,返回值是 null,但是函數(shù)類型是 int,在轉(zhuǎn)換時也出現(xiàn)了 NullPointerException。
所以雖然 HashMap 的 get() 方法不會出現(xiàn) NullPointerException,但是在包裝類和基本類型轉(zhuǎn)換時還是可能會出現(xiàn) NullPointerException ,編程時需要注意。
NullPointerException的一種情況
很久以前剛開始寫代碼的時候經(jīng)常會從一些模板或者map、list或者一些對象里面取值
取到的值很可能是Object或某種類型 如果需要存儲轉(zhuǎn)化成String類型
我們會在后面加一個.toString()方法來強轉(zhuǎn)
Map<String,Object> map = Maps.newHashMap(); String userName = map.get("username").toString();
如果我們?nèi)〉搅艘粋€空值很可能會報空指針異常
我們可以嘗試String mius = "";
String userName = map.get("username")+mius;
這樣就不會報錯了~
好久之前的小問題 分享一下 如有不足請補充,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringCloud之分布式配置中心Spring Cloud Config高可用配置實例代碼
這篇文章主要介紹了SpringCloud之分布式配置中心Spring Cloud Config高可用配置實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04Java中如何使用Gson將對象轉(zhuǎn)換為JSON字符串
這篇文章主要給大家介紹了關(guān)于Java中如何使用Gson將對象轉(zhuǎn)換為JSON字符串的相關(guān)資料,Gson是Google的一個開源項目,可以將Java對象轉(zhuǎn)換成JSON,也可能將JSON轉(zhuǎn)換成Java對象,需要的朋友可以參考下2023-11-11JavaWeb項目實現(xiàn)文件上傳動態(tài)顯示進度實例
本篇文章主要介紹了JavaWeb項目實現(xiàn)文件上傳動態(tài)顯示進度實例,具有一定的參考價值,有興趣的可以了解一下。2017-04-04