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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With