2011-04-26 44 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

相关问题