下面的代码给出了ConcurrentModificationException,特别是转义线,我想知道为什么。 我发现当迭代器被提取或两个线程同时访问列表后添加到列表中时会发生这种情况。但我不认为这是我的例子。ConcurrentModificationException在添加到ArrayList中的吸气剂
什么我做的是传递GameObjects列表作为参数:
camera.render(g, map.getGameObjectHandler().getGameObjects());
消气:
public ArrayList<GameObject> getGameObjects() {
// if (player != null) {
// gameObjects.add(player);
// }
return this.gameObjects;
我后来遍历listbut不删除或添加任何东西。 我只使用迭代器访问每个元素。
我希望我提供了足够的信息,如果需要,我会很乐意提供更多信息。
在此先感谢。
//编辑:
我觉得每个吸气剂被调用时的问题是增加玩家名单。我通过将玩家添加到列表中来修复它。 但我仍然想知道我做错了什么,因为这不是 问题的根源还是它?
//更新:
主循环基本上是这样的:
map.update(); // iterating over the list and calling methods of objects in
// the list [running in main game thread]
repaint(); // calling paintComponentMethod where we pass our list as an
// argument so all its content can be drawn [running in event-
// dispatch-thread !?]`
是否在迭代器迭代时添加到列表中? –
可能是这个问题。如果你提供了一些增加玩家的代码,它可能会更清楚。还可以在抛出ConcurrentModificationException的地方在'ArrayList'和'AbstractList'类中放置一些断点 – esin88
'ConcurrentModificationException'在迭代集合并修改它时发生。这非常简单,并且没有例外。要么不这样做,要么让集合的副本迭代。 – Kayaman