ArrayIndexOutOfBoundsException异常,以及如何防止

知识共享许可协议 版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

数组越界 -->>指使用非法索引访问数组。索引为负值或大于或等于数组的大小。

举个例子

int[] array = new int[5];
int boom = array[10]; // 这里就会抛出异常

如何避免,这里就要注意数组的索引
数组的索引不是从1开始的

int[] array = new int[5];
// ... 这里填充数组 ...
for (int index = 1; index <= array.length; index++)
{
    System.out.println(array[index]);
}

这将忽略第一个元素(索引0),并在索引为5时抛出异常。这里的有效索引包含0-4。
所以应该从(索引0)开始遍历。

for (int index = 0; index < array.length; index++)
{
    System.out.println(array[index]);
}

猜你喜欢

转载自blog.csdn.net/qq_35548458/article/details/93217874