0
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.

3
  • 1
    What's the relationship between chat.getRecipients and plugin.inreview? Commented Oct 13, 2011 at 22:22
  • @JonSkeet There is no relation. This is for Minecraft. chat.getRecipients returns the list of players that will be messaged... this.plugin.inreview is a Hashmap with a key and a value. Commented Oct 13, 2011 at 22:30
  • if you comment out chat.getRecipients().remove(key);just for test and run it do you still get this error. I think there is a relationship and you are removing elements from same collection while iterating. Commented Oct 13, 2011 at 22:36

2 Answers 2

2

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);
})
Sign up to request clarification or add additional context in comments.

Comments

1

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?

3 Comments

I agree, but prefer LinkedList to Vector. No good reason for my preference though.
getRecipients() is different from plugin.inreview.
The irony is that this identical bit of code is used in another .Java file and works perfectly fine. Both are setup the same way...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.