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

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

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

当前回答

在代码中,您已经访问了从索引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');
}

其他回答

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

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

int intArray[] = new int[5];

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

intArray[5];

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

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

或:

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

根据贵公司守则:

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

如果你检查 System.out.print (name.length);

你会得到3;

也就是说你的名字长度是3

你的循环从0运行到3 它应该是0到2或者1到3

回答

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

摘自这篇优秀的文章:ArrayIndexOutOfBoundsException in for循环

简单来说:

在最后的迭代中

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

我将等于name。长度,这是一个非法索引,因为数组下标是从零开始的。

您的代码应该如下所示

for (int i = 0; i < name.length; i++) 
                  ^

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

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

例如:

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循环,那就这样做。)