Java 中的 ArrayIndexOutOfBounds 与 ArrayStoreException?
数组是一种数据结构/容器/对象,用于存储相同类型元素的固定大小的顺序集合。数组的大小/长度在创建时确定。
数组中元素的位置称为索引或下标。数组的第一个元素存储在索引 0 处,第二个元素存储在索引 1 处,依此类推。

创建数组
在 Java 中,数组被视为引用类型,您可以使用类似于对象的 new 关键字创建数组,并使用索引填充它 −
int myArray[] = new int[7]; myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524;
或者,您可以直接使用花括号赋值,用逗号 (,) 分隔它们,例如 −
int myArray = {1254, 1458, 5687, 1457, 4554, 5445, 7524};
访问数组中的元素
使用表达式访问数组中的每个元素,该表达式包含数组的名称,后跟方括号中所需元素的索引。
System.out.println(myArray[3]); //打印 1457
ArrayIndexOutOfBoundsException
通常,数组的大小是固定的,并且使用索引访问每个元素。例如,我们创建了一个大小为 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("Elements in the array are: ");
System.out.println(Arrays.toString(myArray));
Scanner sc = new Scanner(System.in);
System.out.println("Enter the index of the required element: ");
int element = sc.nextInt();
System.out.println("Element in the given index is :: "+myArray[element]);
}
}
但是如果您观察下面的输出,我们请求了索引为 9 的元素,因为它是一个无效索引,因此引发了 ArrayIndexOutOfBoundsException 并且执行终止。
输出
Elements in the array are: [897, 56, 78, 90, 12, 123, 75] Enter the index of the required element: 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at AIOBSample.main(AIOBSample.java:12)
ArrayStoreException
当您创建具有固定大小的特定数据类型的数组并填充它时,如果您存储其数据类型以外的值,则会在运行时抛出 ArrayStoreException。
示例
在下面的 Java 程序中,我们创建一个 Integer 数组并尝试在其中存储一个双精度值。
import java.util.Arrays;
public class ArrayStoreExceptionExample {
public static void main(String args[]) {
Number integerArray[] = new Integer[3];
integerArray[0] = 12548;
integerArray[1] = 36987;
integerArray[2] = 555.50;
integerArray[3] = 12548;
System.out.println(Arrays.toString(integerArray));
}
}
运行时异常
此程序编译成功,但在执行时抛出了 ArrayStoreException。
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double at ther.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:9)

