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

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

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

当前回答

根据贵公司守则:

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');
}

其他回答

我所见过的看似神秘的arrayindexoutofboundsexception最常见的情况,即显然不是由您自己的数组处理代码引起的,是SimpleDateFormat的并发使用。特别是在servlet或控制器中:

public class MyController {
  SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

  public void handleRequest(ServletRequest req, ServletResponse res) {
    Date date = dateFormat.parse(req.getParameter("date"));
  }
}

如果两个线程一起进入SimplateDateFormat.parse()方法,你可能会看到一个ArrayIndexOutOfBoundsException异常。注意SimpleDateFormat类javadoc的同步部分。

确保代码中没有像servlet或控制器那样以并发方式访问线程不安全类(如SimpleDateFormat)的地方。检查servlet和控制器的所有实例变量,寻找可能的可疑对象。

由于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字段长度,它包含组件的数量 数组的。长度可以为正或零。

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
}

这意味着您正在尝试访问一个数组的索引,该索引是无效的,因为它不在边界之间。

例如,这将初始化一个上限为4的基元整数数组。

int intArray[] = new int[5];

程序员从零开始计数。例如,这个会抛出一个ArrayIndexOutOfBoundsException,因为上限是4而不是5。

intArray[5];

你的第一个目标应该是能够合理清晰地解释它的文档:

抛出,表示使用非法索引访问了数组。索引值为负或大于或等于数组的大小。

例如:

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循环,那就这样做。)