ConcurrentModificationException(Java)

Kir*_*gle 4 java iterator concurrentmodification

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
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误.

我的方法看起来像

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();
            }
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

所以我理解这意味着我在迭代器完成之前就改变了它的大小,这就是你得到的错误.这是正确的,因为reactStateChange之一是将对象从hashMap中删除.我如何安全地执行此操作,以便在我删除某些内容时让Iterator提前知道,以便我可以避免此错误.提前致谢.如果需要更多细节,我很乐意满足您的要求.

eri*_*son 8

从基础集合中删除元素并继续迭代的唯一安全方法是使用该remove()方法Iterator.这将删除next()方法返回的最后一个元素Iterator.

在您的情况下,似乎这需要传递Iterator给执行修改的方法(或使其成为实例字段,就像Map对象已经是).