HashMap的get()方法的NullPointerException问题
作者:ItsJingdai 时间:2023-09-23 07:24:12
HashMap的get()方法的NullPointerException
今天写代码发现一个 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 ,编程时需要注意。
NullPointerException的一种情况
很久以前刚开始写代码的时候经常会从一些模板或者map、list或者一些对象里面取值
取到的值很可能是Object或某种类型 如果需要存储转化成String类型
我们会在后面加一个.toString()方法来强转
Map<String,Object> map = Maps.newHashMap();
String userName = map.get("username").toString();
如果我们取到了一个空值很可能会报空指针异常
我们可以尝试String mius = "";
String userName = map.get("username")+mius;
这样就不会报错了~
好久之前的小问题 分享一下 如有不足请补充,希望能给大家一个参考。
来源:https://blog.csdn.net/qq_41512783/article/details/110819487
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JDBC+GUI实现简单学生管理系统
![](https://img.aspxhome.com/file/2023/5/76605_0s.jpg)
c# 网络编程之tcp
java实现动态 代理方法浅析
springboot返回图片流的实现示例
C++指针 详细介绍及总结
Java基础之详解HashSet的使用方法
![](https://img.aspxhome.com/file/2023/7/57727_0s.png)
Java线程Timer定时器用法详细总结
Java Swing JLabel标签的使用方法
![](https://img.aspxhome.com/file/2023/3/68573_0s.jpg)
C#使用Dispose模式实现手动对资源的释放
Android 消息队列模型详解及实例
![](https://img.aspxhome.com/file/2023/2/137472_0s.png)
使用C#编写15子游戏
![](https://img.aspxhome.com/file/2023/3/129633_0s.png)
java ArrayList和Vector的区别详解
Spring 整合 MyBatis的实现步骤
![](https://img.aspxhome.com/file/2023/6/63396_0s.jpg)
java中超过long范围的超大整数相加算法详解(面试高频)
![](https://img.aspxhome.com/file/2023/0/61850_0s.png)
C#中datagridview使用tooltip控件显示单元格内容的方法
springboot项目中使用Swagger的简单示例
![](https://img.aspxhome.com/file/2023/9/62989_0s.png)
Android ListView弹性效果的实现方法
详解在LINUX上部署带有JAR包的JAVA项目
![](https://img.aspxhome.com/file/2023/7/78427_0s.png)
Android保持屏幕常亮唤醒状态的方法
Java之常用类小结案例讲解
![](https://img.aspxhome.com/file/2023/5/67995_0s.png)