Java中ArrayIndexOutOfBoundsException如何避免

访问数组前检查索引范围,确保0 ≤ index

在Java中,ArrayIndexOutOfBoundsException 是一种常见的运行时异常,通常发生在访问数组、List 或其他基于索引的集合时,使用了超出有效范围的索引。避免这个异常的关键在于对索引边界进行合理判断和控制。

1. 访问数组前检查索引范围

每次访问数组元素时,确保索引值在合法范围内(即 0 ≤ index 示例:

不要直接写:
  String value = array[i];
而应先判断:
  if (i >= 0 && i     String value = array[i];
  } else {
    // 处理越界情况
  }

2. 遍历集合时使用增强for循环或正确边界

使用传统for循环时,确保循环条件不会越界。

推荐方式:
- 使用增强for循环(无需手动控制索引)
- 或确保循环变量从0开始,且小于容器长度

正确示例:

int[] arr = {1, 2, 3};
// 推荐:增强for
for (int num : arr) {
  System.out.println(num);
}

// 或标准for,注意边界
for (int i = 0; i   System.out.println(arr[i]);
}

3. 操作List时注意size()变化

在遍历List并同时删除元素时,容易因索引错位导致异常。

解决方法:
- 使用 Iterator 的 remove 方法
- 或使用 ListIterator
- 避免在正向for循环中边遍历边删除

安全删除示例:

Iterator it = list.iterator();
while (it.hasNext()) {
  String item = it.next();
  if (item.equals("toRemove")) {
    it.remove(); // 安全删除
  }
}

4. 对外部输入或参数做有效性校验

如果方法接收索引参数,不能假设它是安全的,必须验证。

例如:
public String getElement(String[] arr, int index) {
  if (arr == null) throw new IllegalArgumentException("数组不能为null");
  if (index = arr.length) {
    throw new IndexOutOfBoundsException("索引越界: " + index);
  }
  return arr[index];
}

基本上就这些。只要在使用索引时保持警惕,加上合理的边界检查,就能有效避免 ArrayIndexOutOfBoundsException。