Skip to content Skip to sidebar Skip to footer

Error When Removing From Arraylist

I am getting this error when I am trying to remove an item from an arraylist after it collides with something else. Below is my AsyncTask and the logcat error that goes with it.

Solution 1:

As the logcat states

     Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 103-2020:00:25.426: E/AndroidRuntime(4905):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
03-2020:00:25.426: E/AndroidRuntime(4905):     at java.util.ArrayList.remove(ArrayList.java:399)
03-2020:00:25.426: E/AndroidRuntime(4905):     at com.jister13.plane.Main$handleCollisions.doInBackground(Main.java:462)

You are trying to access index 1 (second item of Array) when the size is only one, meaning the only available index is 0. It occurs at line 462 of Main.java. Post at least the AsyncTask for more help but you can look there and see why it is trying to access something that has been removed or is otherwise not there

Solution 2:

For all your loop that has the method remove change the code as the following example

for(int i = 0; i < enemies.size(); i++)  

change to

for(int i = enemies.size() - 1; i > -1; i--)  

In another word start from the end of the array and go backward when you try to remove element.

Post a Comment for "Error When Removing From Arraylist"