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]);
}
当前回答
摘自这篇优秀的文章:ArrayIndexOutOfBoundsException in for循环
简单来说:
在最后的迭代中
for (int i = 0; i <= name.length; i++) {
我将等于name。长度,这是一个非法索引,因为数组下标是从零开始的。
您的代码应该如下所示
for (int i = 0; i < name.length; i++)
^
其他回答
这意味着您正在尝试访问一个数组的索引,该索引是无效的,因为它不在边界之间。
例如,这将初始化一个上限为4的基元整数数组。
int intArray[] = new int[5];
程序员从零开始计数。例如,这个会抛出一个ArrayIndexOutOfBoundsException,因为上限是4而不是5。
intArray[5];
在大多数编程语言中,索引都是从0开始的。所以你必须写i<names。长度或i<=names。Length-1代替i<=names.length。
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
}
数组中的每一项都称为一个元素,每个元素都通过它的数值索引来访问。如上图所示,编号从0开始。例如,第9个元素将因此在索引8处被访问。
抛出IndexOutOfBoundsException表示某种类型的索引(例如数组、字符串或向量)超出了范围。
任意数组X,可以从[0到(X.length - 1)]访问
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);