简体   繁体   English

在LinkedList上迭代时出现ConcurrentModificationException

[英]ConcurrentModificationException when iterating on LinkedList

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. 我读到同步化将是另一个想法,但它并不总是正确的apporach。 LogCat shows the ConcurrentModificationException for while (sw.hasNext()) row. LogCat显示while (sw.hasNext())行的ConcurrentModificationException。 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? 我怎么解决这个问题?

You're modifying the Selected_Weapons collection while it's being iterated. 您正在迭代时修改Selected_Weapons集合。 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. 在这种情况下,您可能希望迭代集合,并在迭代所有项目后跟踪要删除的项目。

使用ConcurrentLinkedList怎么样?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM