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]);
}
当前回答
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。
你的第一个目标应该是能够合理清晰地解释它的文档:
抛出,表示使用非法索引访问了数组。索引值为负或大于或等于数组的大小。
例如:
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循环,那就这样做。)
我在这里看到了所有解释如何使用数组以及如何避免索引越界异常的答案。我个人不惜一切代价避免数组。我使用Collections类,这避免了必须完全处理数组下标的所有愚蠢行为。循环构造与支持更容易编写、理解和维护的代码的集合完美地工作。
ArrayIndexOutOfBoundsException名称本身解释了,如果您试图访问超出数组大小范围的索引值,则会发生此类异常。
在你的例子中,你可以从for循环中删除等号。
for(int i = 0; i<name.length; i++)
更好的选择是迭代数组:
for(String i : name )
System.out.println(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++) {