是什么原因导致java.lang.ArrayIndexOutOfBoundsException,我该如何防止它?

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

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

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

答案 1

您的第一个停靠港应该是能够合理清楚地解释它的文档

抛出以指示已使用非法索引访问数组。索引为负数,或者大于或等于数组的大小。

例如:

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(含 0-4)。这里正确的惯用语是:for

for (int index = 0; index < array.length; index++)

(当然,这是假设你需要索引。如果可以改用增强的 for 循环,请执行此操作。


答案 2
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];
}

另请参阅:


更新:根据您的代码片段,

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

索引包含数组的长度。这是超出界限的。您需要替换为 。<=<

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