今天在处理一个问题的时候,需要使用到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代码执行的过程
- 由于我们传入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);
}
- 执行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。
- 将返回的值赋给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函数,要么不获取返回值,要么就需要进行判空处理了。