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

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

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

当前回答

为了避免数组索引越界异常,应该在可以的地方和时候使用增强的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");
}

其他回答

你的第一个目标应该是能够合理清晰地解释它的文档:

抛出,表示使用非法索引访问了数组。索引值为负或大于或等于数组的大小。

例如:

int[] array = new int[5];
int boom = array[10]; // Throws the exception

至于如何避免……嗯,别这么做。小心你的数组索引。

人们有时会遇到的一个问题是认为数组是1索引的,例如。

int[] array = new int[5];
// ... populate the array here ...
for (int index = 1; index <= array.length; index++)
{
    System.out.println(array[index]);
}

这将遗漏第一个元素(索引0),并在索引为5时抛出异常。这里的有效索引是0-4。正确的,地道的for语句应该是:

for (int index = 0; index < array.length; index++)

(当然,这是假设您需要索引。如果你可以使用增强的for循环,那就这样做。)

每当这个异常出现时,它意味着你正在尝试使用一个超出界限的数组索引,或者在外行术语中,你正在请求比你初始化的更多。

为了防止这种情况,总是要确保你没有请求一个数组中不存在的索引,即如果数组长度为10,那么你的索引必须在0到9之间

这个简单的问题就讲到这里,我只想强调Java中的一个新特性,它可以避免所有关于数组中索引的困惑,即使是初学者。Java-8为您抽象了迭代的任务。

int[] array = new int[5];

//If you need just the items
Arrays.stream(array).forEach(item -> { println(item); });

//If you need the index as well
IntStream.range(0, array.length).forEach(index -> { println(array[index]); })

有什么好处?首先是可读性,比如英语。其次,您不需要担心ArrayIndexOutOfBoundsException

对于多维数组,要确保访问正确维度的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]。长度,为了简单)。

在代码中,您已经访问了从索引0到字符串数组长度的元素。的名字。Length给出了字符串对象数组中字符串对象的数量,即3,但你只能访问到索引2名称[2], 因为可以从索引0到name访问数组。长度- 1,你得到名字。对象的长度。

即使在使用for循环时,您已经从索引0开始,并且应该以name结束。长度- 1。在数组a[n]中,您可以从[0]访问到a[n-1]。

例如:

String[] a={"str1", "str2", "str3" ..., "strn"};

for(int i=0; i<a.length(); i++)
    System.out.println(a[i]);

在你的情况下:

String[] name = {"tom", "dick", "harry"};

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n');
}