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

それが私が受け取るエラーです。

私の方法は次のようになります

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の1つが、hashMapからオブジェクトを削除するためのものであるためです。これを安全に行うにはどうすればよいですか。何かを削除したときにIteratorに事前に通知して、このエラーを回避できるようにします。前もって感謝します。詳細が必要な場合は、ご要望にお応えさせていただきます。

4

3 に答える 3

8

基になるコレクションから要素を削除して反復を続行する唯一の安全な方法は、のremove()メソッドを使用することIteratorです。next()これにより、のメソッドによって返された最後の要素が削除されIteratorます。

あなたの場合、これには、変更を実行するメソッドにを渡す必要があるようです(または、オブジェクトがすでにIterator存在するように、インスタンスフィールドにします)。Map

于 2011-04-26T18:51:17.223 に答える
1

iterator.remove()を使用して削除します。

于 2011-04-26T18:51:48.690 に答える
1

もう1つのオプションは、この問題がないConcurrentHashMapを使用することです。これを置換のドロップとして使用でき、残りのコードを変更する必要はありません。

于 2011-04-26T19:20:02.490 に答える