問題描述
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 中刪除對象.如何安全地執行此操作,以便在刪除某些內容時讓迭代器提前知道,這樣我就可以避免此錯誤.提前致謝.如果需要更多詳細信息,我很樂意滿足您的要求.
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.
推薦答案
從底層集合中刪除元素并繼續迭代的唯一安全方法是使用 的 com/javase/6/docs/api/java/util/Iterator.html#remove%28%29" rel="noreferrer">remove()
方法迭代器.這將刪除 Iterator
的 next()
方法返回的最后一個元素.
The only safe way to remove an element from an underlying collection and continue the iteration is to use the remove()
method of the Iterator
. This removes the last element returned by the next()
method of the Iterator
.
在您的情況下,這似乎需要將 Iterator
傳遞給執行修改的方法(或使其成為實例字段,如 Map
對象是已經).
In your case, it appears that this would require passing the Iterator
to the method that performs the modification (or make it an instance field, like the Map
object is already).
這篇關于并發修改異常 (Java)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!