You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Java代码触发java.lang.IndexOutOfBoundsException异常排查

错误排查与修复方案

错误原因分析

1. ArrayList初始化使用错误

new ArrayList<Boolean>(candies.length)仅指定了列表的初始容量,并未向列表中添加任何元素,此时列表实际长度为0。循环中调用res.set(i, ...)尝试修改索引i的元素,但该索引位置不存在,直接触发IndexOutOfBoundsException。

2. 多余的数组排序(逻辑错误)

代码中对candies数组执行排序操作,会破坏原数组的元素顺序。而题目要求返回的布尔列表顺序需与原数组中孩子的顺序对应,排序后结果顺序完全错乱,属于逻辑错误。

3. 空数组边界未处理

若传入的candies数组为空(长度为0),candies[candies.length-1]会访问索引-1,同样触发数组越界异常。

修复后的代码

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
        // 处理空数组情况
        if (candies.length == 0) {
            return new ArrayList<>();
        }
        
        // 遍历原数组找最大值,无需排序
        int max = candies[0];
        for (int candy : candies) {
            if (candy > max) {
                max = candy;
            }
        }
        
        List<Boolean> res = new ArrayList<>(candies.length);
        for (int candy : candies) {
            // 使用add添加元素,而非修改不存在的索引
            res.add(candy + extraCandies >= max);
        }
        return res;
    }            
}

关键修复点说明

  • 替换res.set(i, ...)为res.add(...):add方法将元素追加到列表末尾,正确构建对应长度的列表。
  • 移除Arrays.sort(candies):通过遍历原数组获取最大值,保留原数组顺序,保证结果顺序符合要求。
  • 添加空数组判断:避免空数组时访问无效索引的问题。

内容的提问来源于stack exchange,提问作者user21285927

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 08:12:37