Reputation: 6207
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.
Upvotes: 8
Views: 18634
Reputation: 4239
An important note about for-each:
The for-each loop is used with both collections and arrays. It's intended to simplify the most common form of iteration, where the iterator or index is used solely for iteration, and not for any other kind of operation, such as removing or editing an item in the collection or array. When there is a choice, the for-each loop should be preferred over the for loop, since it increases legibility.
In your case using iterator is preferable.
Can you also post the update()
method of Baseitem
?
Upvotes: 1
Reputation: 10117
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);
Upvotes: 2
Reputation: 3814
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.
Upvotes: 15