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]);
}
当前回答
这个简单的问题就讲到这里,我只想强调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
其他回答
对于给定的数组,数组的长度是3。的名字。但是因为它存储的是从索引0开始的元素,所以它的最大索引是2。
因此,代替'i**<=name。长度'你应该写'i<**name。长度',以避免'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和控制器的所有实例变量,寻找可能的可疑对象。
如果您使用数组的长度来控制for循环的迭代,请始终记住数组中第一项的索引为0。所以数组中最后一个元素的下标比数组的长度小1。
你的第一个目标应该是能够合理清晰地解释它的文档:
抛出,表示使用非法索引访问了数组。索引值为负或大于或等于数组的大小。
例如:
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循环,那就这样做。)
根据贵公司守则:
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');
}