Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

ArrayIndexOutOfBoundsException trong Java là gì?


Mảng là cấu trúc dữ liệu/container/object lưu trữ tập hợp cố định các phần tử cùng kiểu. Kích thước mảng xác định khi tạo.

Vị trí phần tử gọi là index hoặc subscript. Phần tử đầu ở index 0, thứ hai ở index 1, v.v.

ArrayIndexOutOfBoundsException trong Java là gì?

Mỗi phần tử truy cập bằng biểu thức: tên mảng theo sau index trong ngoặc vuông.

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

Mảng kích thước cố định, truy cập bằng index. Ví dụ mảng size 7, index hợp lệ 0 đến 6 (length-1).

Khi dùng giá trị âm hoặc ≥ size mảng, ArrayIndexOutOfBoundsException ném ra.

Ví dụ code sau hiển thị mảng, yêu cầu nhập index. Size 7, index hợp lệ 0-6.

Ví dụ

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]);    } }

Nhưng output dưới nhập index 9 (không hợp lệ) ném ArrayIndexOutOfBoundsException và dừng.

Kết quả

Run time exception −

Elements in the array are: [1254, 1458, 5687, 1457, 4554, 5445, 7524] Enter the index of the required element: 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7    at AIOBSample.main(AIOBSample.java:12)