Java - Iterate Hashmap?
Iterator<Player> i开发者_运维知识库terator = plugin.inreview.keySet().iterator();
while (iterator.hasNext()) {
Player key = (Player) iterator.next();
chat.getRecipients().remove(key);
}
This throws an: java.util.NoSuchElementException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
Any ideas as to why this is happening? When this occurs, there is one key (with one value) in the map.
Better solution for iterating a hashmap (java 8+):
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
// ...
// ...
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
})
My guess is that your getRecipients()
returns the same collection as plugin.inreview
!
This would mean that you try to remove an element from the collection while you are iterating over it. This is of course bad.
Instead, you should do this
Vector toRemove=new Vector();
Iterator<Player> iterator = plugin.inreview.keySet().iterator();
while (iterator.hasNext()) {
Player key = (Player) iterator.next();
toRemove.add(key);
}
chat.getRecipients().removeAll(toRemove);
Another possibility is that you have several threads?
精彩评论