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/46459898/

相关文章:

php - 我可以将数组绑定(bind)到 PDO 查询中的 IN() 条件吗?

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

java - 为什么 JSP(和 JSTL/EL)采用与 Servlet 或 JSF 不同的方式来执行资源注入(inject)?

java - Abstract设置不同的逻辑

jquery - 客户端无法解析JSon,什么问题?

c++ - Try-Catch 不捕获异常

C++继承另一个库中的库异常以将它们传递给调用代码

java - FileReader read() 方法打印不正确。除了 int(ASCII rep) 到 char 之外,我还需要做任何额外的转换吗?

java - 将 AES key 安全地存储在 Android 设备中

c# - c#中的托管指针数组