是什么导致java.lang.arrayindexoutofboundsexception以及如何防止它?

jum4pzuy  于 2021-07-12  发布在  Java
关注(0)|答案(17)|浏览(308)

是什么 ArrayIndexOutOfBoundsException 我的意思是我该怎么摆脱它?
下面是触发异常的代码示例:

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

thtygnil16#

来自这篇优秀的文章:for循环中的arrayindexoutofboundsexception
简而言之:
在的最后一次迭代中

for (int i = 0; i <= name.length; i++) {
``` `i` 将等于 `name.length` 这是非法索引,因为数组索引是基于零的。
你的代码应该是

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

drkbr07n

drkbr07n17#

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

相关问题