Java使用Map获取put返回值的时候遇到的空指针异常

今天在处理一个问题的时候,需要使用到Map的put方法的返回值,结果遇到了一个空指针的异常,异常log如下

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nida.kotlindemo/com.nida.kotlindemo.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.Integer.intValue()’ on a null object reference

怎么引起的呢?
Map的定义

Map<String, Integer> map = new HashMap<>();

put的代码

int a = map.put("nida", 3);

然后,一运行就报空指针异常。我最初开始以为是在put的时候,直接传入的int 3导致的,然后尝试直接传入Integer,问题还是一样的。最终查阅资料才找到原因。

分析下上面put代码执行的过程

  1. 由于我们传入put的第二个参数为int的3,所以此时会有一个装箱的过程,也就是调用Integer的静态方法valueOf,将int装箱为Integer
  public static Integer valueOf(int i) {
      if (i >= IntegerCache.low && i <= IntegerCache.high)
          return IntegerCache.cache[i + (-IntegerCache.low)];
      return new Integer(i);
  }
  1. 执行Map的put函数
 public V put(K key, V value) {
      return putVal(hash(key), key, value, false, true);
  }

我们看到,put函数是有返回值的。如果当前put的key的value在put之前,map里面是存在的,那么就返回之前已经存在的value对象,如果不存在那么就返回null。
注意:Map里面只能存放对象,不能存放基本类型,例如int,需要使用Integer。

  1. 将返回的值赋给int a。由2可知,由于我们是第一次put,map里面不存在对应的value,那么此时返回的Integer对象肯定是null。此时,由于需要赋给int a,那么,就必须对此Integer对象执行拆箱操作。

Integer对象的拆箱操作

 /**
   * Returns the value of this {@code Integer} as an
   * {@code int}.
   */
  public int intValue() {
      return value;
  }

返回的Integer对象是null,此时执行拆箱操作肯定就会报空指针异常了。

所以,使用map的put函数,要么不获取返回值,要么就需要进行判空处理了。


参考
关于int和Integer互转的问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值