java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

标签 java arrays exception arrayindexoutofboundsexception

ArrayIndexOutOfBoundsException 是什么意思以及如何摆脱它?

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

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

最佳答案

您的第一个停靠港应该是documentation这解释得相当清楚:

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

至于如何避免……嗯,不要这样做。请小心您的数组索引。

人们有时会遇到的一个问题是认为数组是 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 循环,那就这样做。)

关于java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55973706/

相关文章:

java - 多个 HttpAsyncClient 被认为是一种不好的做法吗?

java - 当我使用 computeIfAbsent 计算斐波那契数时,hashmap size() 返回不正确的值

java - 自定义 session 并且不点击 Application::newSession

symfony - Symfony 验证器的注释返回 "annotation was never imported exception"

java - 在Java中,我们抛出的异常不会被默认处理程序捕获?正确的

java - 进行自己的查询 Google Analytics (Java)

c - 'C' 二维数组的段错误

javascript - 将三个数组合并成一个字符串

c# - 在 C# 中,为什么数组上的 Equals() 方法只比较它们的引用,而不是它们的实际内容

android - GcWatcher.finalize 10 秒后超时