gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:47:49 27 4
gpt4 key购买 nike

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

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

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

最佳答案

您的第一个 call 端口应该是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(含0和4)。正确,惯用的 for语句如下:
for (int index = 0; index < array.length; index++)

(当然,这是假设您需要索引的。如果可以使用增强的for循环,请这样做。)

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com