Java – why does concurrentmodificationexception appear when deleting from HashMap?

I want to delete a project from HashMap by applying criteria Consider the following codes:

Set<Foo> set = myMap.keySet();
Iterator<Foo> itr = set.iterator();
while (itr.hasNext())
{
    Foo foo = itr.next();
    if (foo.toString().length() < 3) {
        myMap.remove(foo); //remove the pair if key length is less than 3
    }
}

So I got a concurrentmodificationexception because I was modifying HashMap during the iteration What should I do? Is there any other way to search my criteria and execute the remove command at the end so that I can avoid this exception?

Solution

Use ITR Remove() instead of mymap remove(o.toString())

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>