简体   繁体   中英

Java - Iterate Hashmap?

Iterator<Player> iterator = 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM