我不确定为什么我的这部分代码会导致错误,但我知道如果我从列表中删除一个项目并且我只是同时遍历它,我会得到这个异常。我读到同步将是另一个想法,但它并不总是正确的方法。 LogCat 显示 while (sw.hasNext())
行的 ConcurrentModificationException。请注意,我的代码的其他部分对列表完全没有影响。
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);
}
}
}
}
我该如何解决这个问题?
最佳答案
您正在迭代 Selected_Weapons 集合。违规行实际上是:
Selected_Weapons.remove(www);
在这种情况下,您可能想要遍历集合,并在遍历所有项目后跟踪要删除的项目。
关于java - 在 LinkedList 上迭代时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791190/