Java中的ArrayIndexOutOfBoundsException和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]); //prints 1457
ArrayIndexOutOfBoundsException(数组索引越界异常)
通常,数组是固定大小的,每个元素都使用索引访问。例如,我们创建了一个大小为7的数组。那么访问此数组元素的有效表达式将是a[0]到a[6](length-1)。
每当您使用负值或大于等于数组大小的值时,都会抛出**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数组并尝试在其存储一个double值。
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)
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP