为什么会发生 ArrayIndexOutOfBoundsException 以及如何在 Android 中避免它?
问题描述:
为什么会出现ArrayIndexOutOfBoundsException
以及在Android中如何避免?
Why does ArrayIndexOutOfBoundsException
occur and how to avoid it in Android?
答
当您尝试访问不存在的数组项时抛出此异常:
This exception is thrown when you try to access an array item that doesn't exist:
String [] myArray = new String[2];
myArray[2] = "something"; // Throws exception
myArray[-1] = "something"; // Throws exception
在访问数组项之前,您应该检查索引是否为负且不大于数组长度.
You should check that your index is not negative and not higher than the array length before accessing an array item.