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用于将对象从哈希映射中移除。我该如何安全地做到这一点,以便当我删除某些东西时,它可以提前知道迭代器,以便我可以避免此错误。提前致谢。如果需要更多细节,我很乐意满足您的要求。
作为一方的评论:对getCreatures()。get(...)的调用是没有必要的。你已经拥有了你得到的物体。它是什么'iterator.next()'返回... – subsub 2011-04-26 19:01:56
可能重复[迭代通过集合,避免ConcurrentModificationException在循环中删除](http://stackoverflow.com/questions/223918/iterating-through-a- collection-avoid-concurrentmodificationexception-when-re) – Raedwald 2016-03-28 14:32:27