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)
廣告