无处不在的空指针异常

代码可能在`zhangs[index++]=counts.get(coins[index])`这行抛出空指针异常,原因在于`counts.get()`可能返回null。问题在于`index`先自增,可能导致`coins[index]`越界。解决方案是调整循环逻辑,或者使用增强型for循环遍历`counts`。
摘要由CSDN通过智能技术生成
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 ++;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值