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

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

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

当前回答

这个简单的问题就讲到这里,我只想强调Java中的一个新特性,它可以避免所有关于数组中索引的困惑,即使是初学者。Java-8为您抽象了迭代的任务。

int[] array = new int[5];

//If you need just the items
Arrays.stream(array).forEach(item -> { println(item); });

//If you need the index as well
IntStream.range(0, array.length).forEach(index -> { println(array[index]); })

有什么好处?首先是可读性,比如英语。其次,您不需要担心ArrayIndexOutOfBoundsException

其他回答

我所见过的看似神秘的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和控制器的所有实例变量,寻找可能的可疑对象。

根据贵公司守则:

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

在大多数编程语言中,索引都是从0开始的。所以你必须写i<names。长度或i<=names。Length-1代替i<=names.length。

对于任何长度为n的数组,数组元素的索引将从0到n-1。

如果您的程序试图访问数组索引大于n-1的任何元素(或内存),则Java将抛出ArrayIndexOutOfBoundsException

这里有两种我们可以在程序中使用的解决方案

保持数: For (int count = 0;计数< array.length;计数+ +){ System.out.println(阵列[数]); } 或者其他循环语句 Int count = 0; While (count < array.length) { System.out.println(阵列[数]); 数+ +; } 一个更好的方法是使用for循环,在这种方法中,程序员不需要担心数组中元素的数量。 for(String str: array) { System.out.println (str); }