下面代码运行会报错:java.lang.NullPointerException
public class JZ39 {
public int majorityElement(int[] nums) {
Map<Integer, Integer> numMap = new HashMap<>();
int len = nums.length;
for (int n : nums) {
int curTimes = numMap.get(n);
if (curTimes >= len / 2) {
return n;
}
numMap.put(n, curTimes + 1);
}
return -1;
}
public static void main(String[] args) {
JZ39 jz39 = new JZ39();
System.out.println(jz39.majorityElement(new int[]{2, 3, 4, 2}));
}
}
解析:
HashMap的get方法,返回的是 value 类型的对象,这里为 Integer
当对应 key 的 value 不存在,就会返回 null
当使用基本类型 int 接收这个返回值(Integer),会自动拆箱:v.valueOf(V)
相当于:
Integer a = null;
int b = a.intValue();
就会产生开头所说的错误。