是什么导致了 java.lang.ArrayIndexOutOfBoundsException 异常?我该如何预防?

新手上路,请多包涵

ArrayIndexOutOfBoundsException 是什么意思,我该如何摆脱它?

这是触发异常的代码示例:

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

原文由 Aaron 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 944
2 个回答

您的第一个停靠点应该是合理清楚地解释它的 文档

抛出以指示已使用非法索引访问数组。索引为负数或大于或等于数组的大小。

例如:

 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 循环,那就这样做吧。)

原文由 Jon Skeet 发布,翻译遵循 CC BY-SA 3.0 许可协议

if (index < 0 || index >= array.length) {
    // Don't use this index. This is out of bounds (borders, limits, whatever).
} else {
    // Yes, you can safely use this index. The index is present in the array.
    Object element = array[index];
}

也可以看看:


更新:根据您的代码片段,

 for (int i = 0; i<=name.length; i++) {

索引包括数组的长度。这是越界的。您需要将 <= 替换为 <

 for (int i = 0; i < name.length; i++) {

原文由 BalusC 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题