HashMap的get()方法的NullPointerException问题

2022-07-21,,

目录
  • hashmap的get()方法的nullpointerexception
  • nullpointerexception的一种情况
    • 我们会在后面加一个.tostring()方法来强转

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;

这样就不会报错了~

好久之前的小问题 分享一下 如有不足请补充,希望能给大家一个参考,也希望大家多多支持。

《HashMap的get()方法的NullPointerException问题.doc》

下载本文的Word格式文档,以方便收藏与打印。