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

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

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

当前回答

ArrayIndexOutOfBoundsException名称本身解释了,如果您试图访问超出数组大小范围的索引值,则会发生此类异常。

在你的例子中,你可以从for循环中删除等号。

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

更好的选择是迭代数组:

for(String i : name )
      System.out.println(i);

其他回答

不能迭代或存储超过数组长度的数据。在这种情况下,你可以这样做:

for (int i = 0; i <= name.length - 1; i++) {
    // ....
}

或:

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

ArrayIndexOutOfBoundsException表示您正在尝试访问一个不存在或超出该数组界限的数组索引。数组索引从0开始,以长度- 1结束。

在你的情况下

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n'); // i goes from 0 to length, Not correct
}

当你试图访问时,ArrayIndexOutOfBoundsException会发生 这个名字。长度索引的元素不存在(数组索引以长度-1结束)。只需将<=替换为<就可以解决这个问题。

for(int i = 0; i < name.length; i++) {
    System.out.print(name[i] +'\n');  // i goes from 0 to length - 1, Correct
}

根据贵公司守则:

String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<=name.length; i++) {
  System.out.print(name[i] +'\n');
}

如果你检查 System.out.print (name.length);

你会得到3;

也就是说你的名字长度是3

你的循环从0运行到3 它应该是0到2或者1到3

回答

String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<name.length; i++) {
  System.out.print(name[i] +'\n');
}

每当这个异常出现时,它意味着你正在尝试使用一个超出界限的数组索引,或者在外行术语中,你正在请求比你初始化的更多。

为了防止这种情况,总是要确保你没有请求一个数组中不存在的索引,即如果数组长度为10,那么你的索引必须在0到9之间

你可以在函数风格中使用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