MeWrite Docs

ArrayIndexOutOfBoundsException

Java配列のインデックスが範囲外の場合に発生するエラー

概要

ArrayIndexOutOfBoundsException は、配列の要素にアクセスする際に、存在しないインデックスを指定した場合に発生する実行時例外です。

エラーメッセージ

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
java.lang.ArrayIndexOutOfBoundsException: -1

原因

1. 配列のサイズを超えたインデックス

1
2
int[] numbers = new int[3]; // インデックス 0, 1, 2 のみ有効
numbers[3] = 10; // ArrayIndexOutOfBoundsException

2. 負のインデックス

1
2
int[] arr = {1, 2, 3};
System.out.println(arr[-1]); // ArrayIndexOutOfBoundsException

3. ループでの境界エラー

1
2
3
4
int[] arr = {1, 2, 3};
for (int i = 0; i <= arr.length; i++) { // <= は間違い
    System.out.println(arr[i]);
}

解決策

1. 境界チェックを追加

1
2
3
4
5
6
7
8
int[] arr = {1, 2, 3};
int index = 5;

if (index >= 0 && index < arr.length) {
    System.out.println(arr[index]);
} else {
    System.out.println("インデックスが範囲外です");
}

2. 拡張forループを使用

1
2
3
4
5
6
int[] arr = {1, 2, 3};

// インデックスを使わない安全なループ
for (int num : arr) {
    System.out.println(num);
}

3. Streamsを使用

1
2
int[] arr = {1, 2, 3};
Arrays.stream(arr).forEach(System.out::println);

4. ArrayListを使用

1
2
3
4
5
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));

// getメソッドは範囲外でIndexOutOfBoundsExceptionをスロー
// しかし、追加・削除が柔軟
list.add(4);

関連エラー

関連エラー

Java の他のエラー

最終更新: 2025-12-17