java – 从HashMap中删除时为什么会出现ConcurentModificationEx
发布时间:2020-12-15 01:59:51 所属栏目:Java 来源:网络整理
导读:我想通过应用标准从HashMap中删除一个项目.考虑以下代码: SetFoo set = myMap.keySet();IteratorFoo itr = set.iterator();while (itr.hasNext()){ Foo foo = itr.next(); if (foo.toString().length() 3) { myMap.remove(foo); //remove the pair if key l
我想通过应用标准从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 } } 所以我得到了一个ConcurentModificationException,因为在迭代期间我正在修改HashMap.我该怎么办?有没有其他方法来搜索我的标准并在最后执行remove命令,以便我可以避免此异常? 解决方法
使用itr.remove()而不是myMap.remove(o.toString())
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |