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

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

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

当前回答

这个简单的问题就讲到这里,我只想强调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

其他回答

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

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

或:

for (int i = 0; i < name.length; 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');
}

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

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

例如:

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

对于任何长度为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); }

由于i<=name,你会得到ArrayIndexOutOfBoundsException。长度的部分。的名字。Length返回字符串名称的长度,即3。因此,当您试图访问名称[3]时,它是非法的,并抛出异常。

解决代码:

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

它在Java语言规范中定义:

公共final字段长度,它包含组件的数量 数组的。长度可以为正或零。