问题
Why does ArrayIndexOutOfBoundsException
occur and how to avoid it in Android?
回答1:
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.
回答2:
Why does ArrayIndexOutOfBoundsException occur [...]
Here is a quotation from the Java Language Specification: 10.4 Array Access:
All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.
[...] and how to avoid it in Android?
You make sure you're indices are within the range [0...yourArray.length
-1].
(Note the -1 above. Arrays are 0-indexed which means that you'll find the first element at index 0, and the last at length-1.)
回答3:
It means, as said, that you access an array-item that does not exist.
Most of the time it is because someone asks for the size of an array (length) and then tries to read the last item as array[length]
.
But arrays start at 0, so the last you can read is array[length-1]
Sollution is ofcourse do not access items that do not exist
回答4:
This exception has nothing to do with Android because Android Applications uses Java Programming language. Rather you should ask like how to avoid it in Java?
.
And the bottom line is that you are trying to access the value at the invalid index in your Array.
Read the official documentation here:
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
来源:https://stackoverflow.com/questions/4958235/why-does-arrayindexoutofboundsexception-occur-and-how-to-avoid-it-in-android