Reputation: 1670
I am not sure why this part of my code causes error but I know that if I remove an item from a list and I am just iterating through it at the same time I get this exception. I read that syncronizing would be another idea, but it is not always the right apporach. LogCat shows the ConcurrentModificationException for while (sw.hasNext())
row. Please note that other part of my code has abosultely no effect on the Lists.
Iterator<Weapons> sw = Selected_Weapons.iterator();
while (sw.hasNext()) {
Weapons www = sw.next();
if (www.getY()<648){
Iterator<Container> cit2 = Containers.iterator();
while (cit2.hasNext()) {
Container c = cit2.next();
if (c.getWeaponID()==www.id){
c.setWeaponID(-1);
c.setIsEmpty(true);
Selected_Weapons.remove(www);
}
}
}
}
How can I solve this?
Upvotes: 1
Views: 124
Reputation: 16834
You're modifying the Selected_Weapons collection while it's being iterated. The offending line is actually:
Selected_Weapons.remove(www);
In this case, you might want to iterate over the collection, and just keep track of which ones you want to remove after you've iterated over all of the items.
Upvotes: 4