【问题标题】:ConcurrentModificationException (Java)并发修改异常 (Java)
【发布时间】: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 中删除对象。如何安全地执行此操作,以便在删除某些内容时让迭代器提前知道,这样我就可以避免此错误。提前致谢。如果需要更多详细信息,我很乐意满足您的要求。

【问题讨论】:

标签: java iterator concurrentmodification


【解决方案1】:

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

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

【讨论】:

  • 啊,当我在等待答案时,我想到了在 API 中查找 Iterator 并找到您刚刚告诉我的内容。我觉得现在问有点傻。谢谢您确实帮助了我,因为我将删除放在之后而不是之前,但我仍然收到错误。大声笑
【解决方案2】:

您使用 iterator.remove() 删除它。

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 嘿,我在看这个,但它不会让我创建它。说找不到我尝试导入的符号,但可能是我使用了错误的符号?
    • nvm 我发现它是 import java.util.concurrent.ConcurrentHashMap;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 2012-11-21
    • 1970-01-01
    • 2016-11-19
    相关资源
    最近更新 更多