Java – learn about ArrayList indexoutofboundsexception in Android

I get a lot of indexoutofboundseception from any ArrayList I use Most of the time it works, but sometimes I encounter this annoying error on the ArrayLists used in my project

The main reason is always

java.util.ArrayList.throwindexoutofboundsexception: Invalid index 3,size is 3

or

java.util.ArrayList.throwindexoutofboundsexception: Invalid index 0,size is 0

Help me understand the main reason for this mistake, because no matter how many answers I searched, they didn't completely help me

Solution

This means that you have an ArrayList, which has three elements, and you can get each element, such as position 0,1,2 And you are trying to read the fourth element that does not exist in the ArrayList

This means that you have an empty ArrayList and you are trying to read the first element

ArrayIndexOutOfBoundsException – example

The array index out of range exception is a Java exception thrown by the program trying to access a. the element is located outside the array limit, so the word "out of bounds" In other words, the plan is trying to access the elements at the index outside the array boundary To understand array boundaries, let's consider the following figure:

The figure above contains an array of seven elements Each element in the array has its own index / position In Java, the index always ends with 0 and the length of array - 1 For example, the above array consists of seven elements, so its index starts at 0 and ends at 6 (7-1) Attempting to access an element with an index less than 0 or greater than 6 will cause java to throw an ArrayIndexOutOfBoundsException

Read more about ArrayIndexOutOfBoundsException – examples, causes & fixes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>