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]);
}
当前回答
由于i<=name,你会得到ArrayIndexOutOfBoundsException。长度的部分。的名字。Length返回字符串名称的长度,即3。因此,当您试图访问名称[3]时,它是非法的,并抛出异常。
解决代码:
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i < name.length; i++) { //use < insteadof <=
System.out.print(name[i] +'\n');
}
它在Java语言规范中定义:
公共final字段长度,它包含组件的数量 数组的。长度可以为正或零。
其他回答
对于给定的数组,数组的长度是3。的名字。但是因为它存储的是从索引0开始的元素,所以它的最大索引是2。
因此,代替'i**<=name。长度'你应该写'i<**name。长度',以避免'ArrayIndexOutOfBoundsException'。
你可以在函数风格中使用Optional来避免NullPointerException和ArrayIndexOutOfBoundsException:
String[] array = new String[]{"aaa", null, "ccc"};
for (int i = 0; i < 4; i++) {
String result = Optional.ofNullable(array.length > i ? array[i] : null)
.map(x -> x.toUpperCase()) //some operation here
.orElse("NO_DATA");
System.out.println(result);
}
输出:
AAA
NO_DATA
CCC
NO_DATA
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++) {
不能迭代或存储超过数组长度的数据。在这种情况下,你可以这样做:
for (int i = 0; i <= name.length - 1; i++) {
// ....
}
或:
for (int i = 0; i < name.length; i++) {
// ...
}