是什么导致 java.lang.ArrayIndexOutOfBoundsException 以及

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?(是什么导致 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?)

本文介绍了是什么导致 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 以及