【发布时间】:2011-04-26 18:48:34
【问题描述】:
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
这是我收到的错误。
我的方法看起来像
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 之一是要从 hashMap 中删除对象。如何安全地执行此操作,以便在删除某些内容时让迭代器提前知道,这样我就可以避免此错误。提前致谢。如果需要更多详细信息,我很乐意满足您的要求。
【问题讨论】:
-
作为旁注:无需调用
getCreatures().get(...)。你已经有了你得到的对象。这是iterator.next()返回的...
标签: java iterator concurrentmodification