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

That is the error I receive.

My method looks like

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();
            }
        }
    }
} 

So what I understand is this means I'm changing the size of the iterator before it is finished and this is the error you get. This is true as one of the reactStateChange is for an object to be removed out of the hashMap. How do I do this safely so that when I remove something it lets the Iterator know ahead of time so I can avoid this error. Thanks in advance. If more details are needed I'd be glad to meet your requests.

4

3 回答 3

8

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

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

于 2011-04-26T18:51:17.223 回答
1

You remove it using iterator.remove().

于 2011-04-26T18:51:48.690 回答
1

另一种选择是使用没有此问题的 ConcurrentHashMap。您可以将其用作替代品,而无需更改其余代码。

于 2011-04-26T19:20:02.490 回答