Java 中的 ArrayIndexOutOfBoundsException

17 Mar 2025 | 阅读 2 分钟

每当我们尝试访问数组中不存在某个索引处的元素时,就会发生 ArrayIndexOutOfBoundsException。换句话说,索引可能是负数,或者超出了数组的大小。

ArrayIndexOutOfBoundsException 是 IndexOutOfBoundsException 的一个子类,它实现了 Serializable 接口。

ArrayIndexOutOfBoundsException 示例

输出

ArrayIndexOutOfBoundsException in Java

ArrayIndexOutOfBoundsException 的构造函数

ArrayIndexOutOfBoundException 的构造函数类型如下:

构造函数描述
ArrayIndexOutOfBoundsException()它构造了一个 ArrayIndexOutOfBoundsException,但没有在控制台中显示任何详细信息。
ArrayIndexOutOfBoundsException(int index)它构造了一个 ArrayIndexOutOfBoundsException,其中 index 变量表示该索引是无效的。
ArrayIndexOutOfBoundsException(String s)它构造了一个 ArrayIndexOutOfBoundsException,并带有指定的详细消息。

如何避免 ArrayIndexOutOfBoundsException

  • 导致 ArrayIndexOutOfBoundsException 发生的最大问题之一是,数组的索引从 0 开始而不是从 1 开始,最后一个元素的索引是数组长度 -1,因此用户在访问数组元素时常常会出错。
  • 在设置循环的起始条件和结束条件时,请务必小心。
  • 如果遇到此类异常,请尝试调试代码。
  • 使用增强 for 循环
    • 增强 for 循环是迭代连续内存分配的循环,它只迭代合法的索引。
      例如:
  • 使用类型安全的迭代器
    • 当类型安全的迭代器在遍历集合并进行修改时,它们不会抛出异常,因为它们会创建集合的快照并对其进行修改。例如:

下一个主题Java 教程