public static Info getInfo(int[] arr) {
HashMap<Integer, Integer> counts = new HashMap<>();
for(int num : arr) {
if(counts.containsKey(num)) {
counts.put(num, counts.get(num) + 1);
} else {
counts.put(num, 1);
}
}
int[] coins = new int[counts.size()];
int[] zhangs = new int[counts.size()];
Iterator<Integer> iterator = counts.keySet().iterator();
int index = 0;
while(iterator.hasNext()) {
System.out.println(index);
coins[index] = iterator.next();
System.out.println(index);
//这一句会出现空指针异常
zhangs[index ++] = counts.get(coins[index]);
//index ++;
}
return new Info(coins, zhangs);
}
在代码中,可能会出现空指针异常的地方是 zhangs[index ++] = counts.get(coins[index]);
这一行。具体来说,counts.get(coins[index])
可能会返回 null
,从而导致空指针异常。
这是因为在这个代码块中,index
在循环中被先自增,再被作为参数传递给 counts.get()
方法。如果 iterator.next()
方法返回的是最后一个元素,那么 coins[index]
将会越界,因为 coins
的长度为 counts
的大小,而不是 arr
的大小。
为了避免空指针异常,可以使用以下修改:
while(iterator.hasNext()) {
coins[index] = iterator.next();
zhangs[index] = counts.get(coins[index]); // 修改此行
index ++;
}
或者使用增强型 for 循环来遍历 counts
:
int index = 0;
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
coins[index] = entry.getKey();
zhangs[index] = entry.getValue();
index ++;
}