Java ConcurrentModificationException异常原因和解决方法
原创
©著作权归作者所有:来自51CTO博客作者霸道流氓的原创作品,请联系作者获取转载授权,否则将追究法律责任
场景
对ArrayList在迭代的时候如果同时对其进行修改就会抛出java.util.ConcurrentModificationException异常。
出现异常的代码:
//删除非此退货单对应的货位
for (BusGoodsLocationVO locationVO : page.getRecords()) {
if (locationVO.getRefundOrderFlag() == 1 && locationVO.getIsSelected() == 0) {
page.getRecords().remove(locationVO);
}
}
实现
使用迭代器就可以解决
Iterator<BusGoodsLocationVO> iterator = page.getRecords().iterator();
while(iterator.hasNext()){
BusGoodsLocationVO locationVO = iterator.next();
if (locationVO.getRefundOrderFlag() == 1 && locationVO.getIsSelected() == 0) {
iterator.remove();
}
}