Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, ArrayList and Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException

Tags:

java

Im iterating through an ArrayList. If I use the old fashion way:

for (int i = 0; i < list.size(); i++)
{
    list.get(i).update();;
}

it runs ok. But with this:

for (Baseitem item : list)
{
    item.update();
}

it fails at the first line, inside ArrayList class: Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException yes, outside I do remove items - but certainly not while iterating. How to solve this? I dont use any threads.

like image 489
John Smith Avatar asked Jun 12 '13 14:06

John Smith


2 Answers

You should avoid modifying elements in a list while iterating that list.

With the for (int i...) loop, you are not iterating the list, so you can modify the elements inside.

In the for (Baseitem item : list) loop, you are iterating the list, so the modification of the elements of the list will raise the ConcurrentModificationException exception.

You have to use the first form of the loop if you want to modify the elements inside it.

like image 146
eternay Avatar answered Nov 09 '22 16:11

eternay


This happened to me because I was iterating through a list for removing all the items, with a for loop.

Example clients : [1, 2, 3]

for(int i=0 ; i<clients.size() /* 3 */ ; i++)
    clients.remove(clients.get(i));

i is going to be 0, 1 and 2, but at the third iteration (i=2) there will be no clients[2], thence ConcurrentModificationException.


How to avoid the problem:

while(clients.size() > 0)
    clients.remove(0);
like image 24
António Almeida Avatar answered Nov 09 '22 16:11

António Almeida