我希望能够通过应用某些条件从HashMap中删除一个条目。请考虑以下代码:
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
}
}
我因为在迭代过程中修改了HashMap而得到了ConcurrentModificationException异常。我该怎么办?有没有其他方法可以搜索我的条件并在最后执行删除命令,以避免这个异常?