Java 中的 ArrayIndexOutOfBoundsException 是什么?

javaobject oriented programmingprogramming

数组是一种数据结构/容器/对象,用于存储相同类型元素的固定大小的顺序集合。数组的大小/长度在创建时确定。

数组中元素的位置称为索引或下标。数组的第一个元素存储在索引 0 处,第二个元素存储在索引 1 处,依此类推。

数组中的每个元素都使用一个表达式来访问,该表达式包含数组的名称,后跟方括号中所需元素的索引。

System.out.println(myArray[3]);
//prints 1457

通常,数组的大小是固定的,每个元素都使用索引来访问。例如,我们创建了一个大小为 7 的数组。那么访问此数组元素的有效表达式将是 a[0] 到 a[6](长度-1)。

每当您使用 –ve 值或大于或等于数组大小的值时,就会抛出 ArrayIndexOutOfBoundsException

例如,如果您执行以下代码,它会显示数组中的元素并要求您提供索引以选择元素。由于数组的大小为 7,因此有效索引将为 0 到 6。

示例

import java.util.Arrays;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String args[]){
      int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};
      System.out.println("数组中的元素为:");
      System.out.println(Arrays.toString(myArray));
      Scanner sc = new Scanner(System.in);
      System.out.println("输入所需元素的索引:");
      int element = sc.nextInt();
      System.out.println("Element in the given index is :: "+myArray[element]);
   }
}

但是,如果您观察以下输出,我们请求了索引为 9 的元素,因为它是无效索引,因此引发了 ArrayIndexOutOfBoundsException 并终止执行。

输出

运行时异常 −

数组中的元素为:
[1254, 1458, 5687, 1457, 4554, 5445, 7524]
输入所需元素的索引:
7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
   at AIOBSample.main(AIOBSample.java:12)

相关文章