What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?(是什么导致 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?)
问题描述
ArrayIndexOutOfBoundsException
是什么意思,我该如何摆脱它?
What does ArrayIndexOutOfBoundsException
mean and how do I get rid of it?
下面是一个触发异常的代码示例:
Here is a code sample that triggers the exception:
String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
System.out.println(names[i]);
}
推荐答案
您的第一个调用端口应该是 documentation 解释得很清楚:
Your first port of call should be the documentation which explains it reasonably clearly:
抛出以指示已使用非法索引访问数组.索引为负数或大于等于数组的大小.
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
例如:
int[] array = new int[5];
int boom = array[10]; // Throws the exception
至于如何避免...嗯,不要那样做.小心你的数组索引.
As for how to avoid it... um, don't do that. Be careful with your array indexes.
人们有时会遇到的一个问题是认为数组是 1 索引的,例如
One problem people sometimes run into is thinking that arrays are 1-indexed, e.g.
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
语句是:
That will miss out the first element (index 0) and throw an exception when index is 5. The valid indexes here are 0-4 inclusive. The correct, idiomatic for
statement here would be:
for (int index = 0; index < array.length; index++)
(当然,这是假设您需要索引.如果您可以改用增强的 for 循环,请这样做.)
(That's assuming you need the index, of course. If you can use the enhanced for loop instead, do so.)
这篇关于是什么导致 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是什么导致 java.lang.ArrayIndexOutOfBoundsException 以及


基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01