ArrayIndexOutOfBoundsException exceptions, and how to prevent

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Array bounds - >> refers to the use of illegal access to an array index. Index is negative or greater than or equal to the size of the array.

for example

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

How to avoid, we should note here index into the array
index of the array is not starting from 1

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

This will ignore the first element (index 0), and throws an exception when the index is 5. Here's effective index contains 0-4.
So you should start traversing from (index 0).

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

Guess you like

Origin blog.csdn.net/qq_35548458/article/details/93217874