下面的代碼給出了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