ArrayIndexOutOfBoundsException是什么意思,我如何摆脱它?

下面是一个触发异常的代码示例:

String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
    System.out.println(names[i]);
}

当前回答

ArrayIndexOutOfBoundsException表示您正在尝试访问一个不存在或超出该数组界限的数组索引。数组索引从0开始,以长度- 1结束。

在你的情况下

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n'); // i goes from 0 to length, Not correct
}

当你试图访问时,ArrayIndexOutOfBoundsException会发生 这个名字。长度索引的元素不存在(数组索引以长度-1结束)。只需将<=替换为<就可以解决这个问题。

for(int i = 0; i < name.length; i++) {
    System.out.print(name[i] +'\n');  // i goes from 0 to length - 1, Correct
}

其他回答

这意味着您正在尝试访问一个数组的索引,该索引是无效的,因为它不在边界之间。

例如,这将初始化一个上限为4的基元整数数组。

int intArray[] = new int[5];

程序员从零开始计数。例如,这个会抛出一个ArrayIndexOutOfBoundsException,因为上限是4而不是5。

intArray[5];

为了避免数组索引越界异常,应该在可以的地方和时候使用增强的for语句。

主要的动机(和用例)是当您迭代时,您不需要任何复杂的迭代步骤。您不能使用增强的for在数组中向后移动或只迭代每个其他元素。

在执行此操作时,您可以保证不会耗尽要迭代的元素,并且您的[修正]示例很容易转换。

代码如下:

String[] name = {"tom", "dick", "harry"};
for(int i = 0; i< name.length; i++) {
    System.out.print(name[i] + "\n");
}

...等价于:

String[] name = {"tom", "dick", "harry"};
for(String firstName : name) {
    System.out.println(firstName + "\n");
}

不能迭代或存储超过数组长度的数据。在这种情况下,你可以这样做:

for (int i = 0; i <= name.length - 1; i++) {
    // ....
}

或:

for (int i = 0; i < name.length; i++) {
    // ...
}

对于多维数组,要确保访问正确维度的length属性可能有些棘手。以下面的代码为例:

int [][][] a  = new int [2][3][4];

for(int i = 0; i < a.length; i++){
    for(int j = 0; j < a[i].length; j++){
        for(int k = 0; k < a[j].length; k++){
            System.out.print(a[i][j][k]);
        }
        System.out.println();
    }
    System.out.println();
}

每个维度都有不同的长度,因此,中间循环和内部循环使用相同维度的length属性(因为a[i]。Length与a[j]. Length相同)。

相反,内部循环应该使用[i][j]。长度(或[0][0]。长度,为了简单)。

对于任何长度为n的数组,数组元素的索引将从0到n-1。

如果您的程序试图访问数组索引大于n-1的任何元素(或内存),则Java将抛出ArrayIndexOutOfBoundsException

这里有两种我们可以在程序中使用的解决方案

保持数: For (int count = 0;计数< array.length;计数+ +){ System.out.println(阵列[数]); } 或者其他循环语句 Int count = 0; While (count < array.length) { System.out.println(阵列[数]); 数+ +; } 一个更好的方法是使用for循环,在这种方法中,程序员不需要担心数组中元素的数量。 for(String str: array) { System.out.println (str); }