场景:
在HashMap集合迭代时进行删除操作
报错:
java.util.ConcurrentModificationException:null
原因:
HashMap里面有个成员属性modCount,用于记录map被修改的次数(当map被put或者remove时++).
而当我们使用迭代器Iterator对map进行遍历的时候,在迭代器创建的时候就将modCount赋予给了迭代器里面expectedModCount。
map.remove()时只会修改modCount++,expectedModCount不变.
因此在下一次迭代器执行next()方法的时候 ,就会因为modeCount和expectedModCount这两个不一致而抛出错误。
解决:
使用迭代器对数据进行删除。
Set<Map.Entry<String, List<Integer>>> entries = tmpMap.entrySet();
if(CollectionUtils.isNotEmpty(entries)){
Iterator<Map.Entry<String, List<Integer>>> itr = entries.iterator();
while (itr.hasNext()) {
Map.Entry<String, List<Integer>> entry = itr.next();
if(null != entry){
itr.remove();
}
}
}