HashMap的get()方法的NullPointerException问题
目录
- HashMap的get()方法的NullPointerException
- 看下面代码
- NullPointerException的一种情况
- 我们会在后面加一个.toString()方法来强转
- 如果我们取到了一个空值很可能会报空指针异常
HashMap的get()方法的NullPointerException 今天写代码发现一个 bug,HashMap的 get() 方法一直报空指针异常,现记录一下。
看下面代码
private HashMapcache; private LinkedList keyList; private int capacity; public LRUCache(int capacity) {cache = new HashMap<>(); keyList = new LinkedList<>(); this.capacity = capacity; }// Put it in the front if usepublic 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)Java API 明确说明当给定的 key 不存在时,会返回 null,不会抛出 NullPointerException 。
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
说明不是这里的问题,那既然会返回 null,好像懂了,如果 key 值不存在,当返回 null 时,如果用基本数据类型接收结果,如下面的代码。
public static void main(String[] args) {HashMapmap = 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类型
【HashMap的get()方法的NullPointerException问题】
我们会在后面加一个.toString()方法来强转
Map map = Maps.newHashMap(); String userName = map.get("username").toString();
如果我们取到了一个空值很可能会报空指针异常
我们可以尝试String mius = "";
String userName = map.get("username")+mius;
这样就不会报错了~
好久之前的小问题 分享一下 如有不足请补充,希望能给大家一个参考,也希望大家多多支持脚本之家。
推荐阅读
- 热闹中的孤独
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 一个人的旅行,三亚
- 布丽吉特,人生绝对的赢家
- 慢慢的美丽
- 尽力
- 一个小故事,我的思考。
- 家乡的那条小河
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量