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

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

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

当前回答

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++) {

其他回答

如果您使用数组的长度来控制for循环的迭代,请始终记住数组中第一项的索引为0。所以数组中最后一个元素的下标比数组的长度小1。

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

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

或:

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

为了避免数组索引越界异常,应该在可以的地方和时候使用增强的for语句。

主要的动机(和用例)是当您迭代时,您不需要任何复杂的迭代步骤。您不能使用增强的for在数组中向后移动或只迭代每个其他元素。

在执行此操作时,您可以保证不会耗尽要迭代的元素,并且您的[修正]示例很容易转换。

代码如下:

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

...等价于:

String[] name = {"tom", "dick", "harry"};
for(String firstName : name) {
    System.out.println(firstName + "\n");
}

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

对于给定的数组,数组的长度是3。的名字。但是因为它存储的是从索引0开始的元素,所以它的最大索引是2。

因此,代替'i**<=name。长度'你应该写'i<**name。长度',以避免'ArrayIndexOutOfBoundsException'。