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 以及


- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01