0

I want to use this method to delete the same names in HashMap but when i try to compile my code, i get ConcurrentModificationException.

public static void removeTheFirstNameDuplicates(HashMap<String, String> map)
    {

        for (Map.Entry<String, String> pair : map.entrySet()){
            String name = pair.getValue();
            removeItemFromMapByValue(map, name);
        }

    }
2
  • Don't get confused between compilation errors and run time exceptions/errors. Commented Feb 21, 2014 at 23:29
  • And google the exception and exception message. This is a duplicate if I ever saw one. Commented Feb 21, 2014 at 23:30

2 Answers 2

2

When you use an "enhanced" for loop such as this:

for (Map.Entry<String, String> pair : map.entrySet()){

There is really an implicit Iterator behind the scenes that gives you a pair on each iteration. Section 14.14.2 of the JLS states:

The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    VariableModifiersopt TargetType Identifier =
        (TargetType) #i.next();
    Statement
}

The Iterator will throw a ConcurrentModificationException if anything modifies the collection while it's iterating it, unless you call the iterator's own remove() method, which removes the current element. You'll have to use an explicit Iterator:

Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator();
while (itr.hasNext())
{
    Map.Entry<String, String> pair = itr.next();
    if (yourCriteriaIsMet)
    {
        itr.remove();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Don't modify data structures while iterating over them - see http://docs.oracle.com/javase/6/docs/api/java/util/ConcurrentModificationException.html.

Comments

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.