ArrayIndexOutOfBoundsException是什么意思,我如何摆脱它?
下面是一个触发异常的代码示例:
String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
System.out.println(names[i]);
}
ArrayIndexOutOfBoundsException是什么意思,我如何摆脱它?
下面是一个触发异常的代码示例:
String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
System.out.println(names[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循环,那就这样做。)
其他回答
每当这个异常出现时,它意味着你正在尝试使用一个超出界限的数组索引,或者在外行术语中,你正在请求比你初始化的更多。
为了防止这种情况,总是要确保你没有请求一个数组中不存在的索引,即如果数组长度为10,那么你的索引必须在0到9之间
摘自这篇优秀的文章:ArrayIndexOutOfBoundsException in for循环
简单来说:
在最后的迭代中
for (int i = 0; i <= name.length; i++) {
我将等于name。长度,这是一个非法索引,因为数组下标是从零开始的。
您的代码应该如下所示
for (int i = 0; i < name.length; i++)
^
ArrayIndexOutOfBounds表示您正在尝试索引数组中未分配的位置。
在这种情况下:
String[] name = { "tom", "dick", "harry" };
for (int i = 0; i <= name.length; i++) {
System.out.println(name[i]);
}
的名字。length是3,因为数组是用3个String对象定义的。 当访问数组的内容时,position从0开始。因为有3个项目,这意味着名字[0]=“tom”,名字[1]=“dick”,名字[2]=“harry” 当你循环时,因为i可以小于或等于name。长度,您正在尝试访问名称[3],该名称不可用。
为了解决这个问题…
In your for loop, you can do i < name.length. This would prevent looping to name[3] and would instead stop at name[2] for(int i = 0; i<name.length; i++) Use a for each loop String[] name = { "tom", "dick", "harry" }; for(String n : name) { System.out.println(n); } Use list.forEach(Consumer action) (requires Java8) String[] name = { "tom", "dick", "harry" }; Arrays.asList(name).forEach(System.out::println); Convert array to stream - this is a good option if you want to perform additional 'operations' to your array e.g. filter, transform the text, convert to a map etc (requires Java8) String[] name = { "tom", "dick", "harry" }; --- Arrays.asList(name).stream().forEach(System.out::println); --- Stream.of(name).forEach(System.out::println);
数组中的每一项都称为一个元素,每个元素都通过它的数值索引来访问。如上图所示,编号从0开始。例如,第9个元素将因此在索引8处被访问。
抛出IndexOutOfBoundsException表示某种类型的索引(例如数组、字符串或向量)超出了范围。
任意数组X,可以从[0到(X.length - 1)]访问
ArrayIndexOutOfBoundsException名称本身解释了,如果您试图访问超出数组大小范围的索引值,则会发生此类异常。
在你的例子中,你可以从for循环中删除等号。
for(int i = 0; i<name.length; i++)
更好的选择是迭代数组:
for(String i : name )
System.out.println(i);