2011-04-26 42 views
4
Exception in thread "main" java.util.ConcurrentModificationException 
Squash the PC dirties the room Violet. The room's state is now dirty 
Lily the animal growls 
The Animal Lily left the room and goes to Green through the west door. 
     at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793) 
     at java.util.HashMap$KeyIterator.next(HashMap.java:828) 
     at homework5.Room.critReactRoomStateChange(Room.java:76) 
     at homework5.PC.play(PC.java:121) 
     at homework5.Main.main(Main.java:41) 
Java Result: 1 

這是我收到的錯誤。ConcurrentModificationException(Java)

我的方法看起來像

public void critReactRoomStateChange(String command, PC pc) { 
    Creature temp = null; 
    Iterator iterator = getCreatures().keySet().iterator(); 
    while (iterator.hasNext()) { 
     String names = iterator.next().toString(); 
     if (!(getCreatures().get(names) instanceof PC)) { 
      temp = getCreatures().get(names); 
      if (temp != null) { 
       temp.reactStateChange(command, pc); 
       temp.checkNewRoom(); 
      } 
     } 
    } 
} 

所以我的理解是,這意味着我改變迭代器的尺寸完成之前,這是你的錯誤。這是真實的,因爲其中一個reactStateChange用於將對象從哈希映射中移除。我該如何安全地做到這一點,以便當我刪除某些東西時,它可以提前知道迭代器,以便我可以避免此錯誤。提前致謝。如果需要更多細節,我很樂意滿足您的要求。

+1

作爲一方的評論:對getCreatures()。get(...)的調用是沒有必要的。你已經擁有了你得到的物體。它是什麼'iterator.next()'返回... – subsub 2011-04-26 19:01:56

+0

可能重複[迭代通過集合,避免ConcurrentModificationException在循環中刪除](http://stackoverflow.com/questions/223918/iterating-through-a- collection-avoid-concurrentmodificationexception-when-re) – Raedwald 2016-03-28 14:32:27

回答

8

從底層集合中移除元素並繼續迭代的唯一安全方法是使用Iteratorremove()方法。這將刪除由Iteratornext()方法返回的最後一個元素。

就你而言,看來這需要將Iterator傳遞給執行修改的方法(或使其成爲實例字段,如Map對象已經)。

+0

啊,當我在等待答案時,我有了在API中查找Iterator的想法,並發現你剛告訴我的東西。我現在問起來感覺有點傻。謝謝,因爲你確實幫助我,因爲我之前而不是之前把刪除,我仍然得到錯誤。哈哈tyty – 2011-04-26 18:59:28

1

您可以使用iterator.remove()將其刪除。

1

另一種選擇是使用沒有此問題的ConcurrentHashMap。您可以使用它作爲替換的替代品,並且不需要更改其餘的代碼。

+0

嘿,我在看這個,但它不會讓我創建它。說找不到符號我嘗試導入,但它也許我使用了錯誤的? – 2011-04-26 19:43:33

+2

nvm我發現它是import java.util.concurrent.ConcurrentHashMap; – 2011-04-26 19:46:07

相關問題