1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Or better yet, call Iterator.remove(). Then you don't need a separate collection.
I dont know how to accept answer when you write it in a comment but I'd accept it at least 5 times. Great and tricky solution! Thanks!
Because it went wrong 1 of 100 times today.. should I put sw.remove(); before the Selected_Weapons.remove(www) ?
0

How about using ConcurrentLinkedList?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.