ArrayIndexOutOfBoundsException
是什么意思,我如何摆脱它?
这是触发异常的代码示例:
String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
System.out.println(names[i]);
}
最佳答案
您的第一个 call 端口应该是documentation,它可以相当清楚地解释它:
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
因此,例如:
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循环,请这样做。)
关于java - 是什么导致java.lang.ArrayIndexOutOfBoundsException,如何防止它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49812164/