HashMap的get()方法的NullPointerException问题

网友投稿 1438 2022-12-08

HashMap的get()方法的NullPointerException问题

HashMap的get()方法的NullPointerException问题

目录HashMap的get()方法的NullPointerException看下面代码NullPointerException的一种情况我们会在后面加一个.toString()方法来强转如果我们取到了一个空值很可能会报空指针异常

HashMap的get()方法的NullPointerException

今天写代码发现一个 bug,HashMap的 get() 方法一直报空指针异常,现记录一下。

看下面代码

private HashMap cache;

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 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 APnBLZrACWpI 明确说明当给定的 key 不存在时,会返回 null,不会抛出 NullPointerException 。

说明不是这里的问题,那既然会返回 null,好像懂了,如果 key 值不存在,当返回 null 时,如果用基本数据类型接收结果,如下面的代码。

public static void main(String[] args) {

HashMap map = new HashMap<>();

int i = map.get(5);

}

这就会将 null 赋给 i ,这里会有一个自动拆箱过程,会调用返回值的 intValue() 方法并将结果赋值给 i,但是这个返回值是 nulnBLZrACWpl,那么 null.intValue() 便会出现 NullPointerException。

最开始的 return cache.get(key); 也是一样,返回值是 null,但是函数类型是 int,在转换时也出现了 NullPointerException。

所以虽然 HashMap 的 get() 方法不会出现 NullPointerException,但是在包装类和基本类型转换时还是可能会出现 NullPointerException ,编程时需要注意。

NullPointerException的一种情况

很久以前刚开始写代码的时候经常会从一些模板或者map、list或者一些对象里面取值

取到的值很可能是Object或某种类型 如果需要存储转化成String类型

我们会在后面加一个.toString()方法来强转

Map map = Maps.newHashMap();

String userName = map.get("username").toString();

如果我们取到了一个空值很可能会报空指针异常

我们可以尝试String mius = "";

String userName = map.get("username")+mius;

这样就不会报错了~

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:解决Map集合使用get方法返回null抛出空指针异常问题
下一篇:详解SpringBoot中JdbcTemplate的事务控制
相关文章

 发表评论

暂时没有评论,来抢沙发吧~