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]);
}
当前回答
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);
其他回答
我在这里看到了所有解释如何使用数组以及如何避免索引越界异常的答案。我个人不惜一切代价避免数组。我使用Collections类,这避免了必须完全处理数组下标的所有愚蠢行为。循环构造与支持更容易编写、理解和维护的代码的集合完美地工作。
数组中的每一项都称为一个元素,每个元素都通过它的数值索引来访问。如上图所示,编号从0开始。例如,第9个元素将因此在索引8处被访问。
抛出IndexOutOfBoundsException表示某种类型的索引(例如数组、字符串或向量)超出了范围。
任意数组X,可以从[0到(X.length - 1)]访问
if (index < 0 || index >= array.length) {
// Don't use this index. This is out of bounds (borders, limits, whatever).
} else {
// Yes, you can safely use this index. The index is present in the array.
Object element = array[index];
}
参见:
Java教程-语言基础-数组
更新:根据您的代码片段,
for (int i = 0; i<=name.length; i++) {
索引包含数组的长度。这是越界的。你需要用<替换<=。
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循环,那就这样做。)
对于多维数组,要确保访问正确维度的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]。长度,为了简单)。