简体   繁体   English

Java - 迭代 Hashmap?

[英]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这会引发: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.发生这种情况时,map 中有一个键(一个值)。

Better solution for iterating a hashmap (java 8+):迭代 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 ! 我的猜测是您的getRecipients()返回与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? 另一种可能是您有多个线程?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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