刚入门的时候,我们想remove掉集合里的某个指定元素,可能第一想到的就是for循环,然后调用list的remove()方法移除该元素:例如下面这段代码:
JsonKit:这是封装解析json数据的工具类(不是本博客讨论的重点,忽略)
List<ShopGoodsEntity> list = JsonKit.parseJson2List(jsonArray, ShopGoodsEntity.class);
if (list != null && list.size() > 0) {
for (ShopGoodsEntity entity : list) {
if (entity.getGoods_id().equals("123456")){
list.remove(entity);
}
}
}
执行这段代码就会报出以下错误:
java.util.ConcurrentModificationException
at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
这是因为循环过程中list.size()的大小变化了,就导致了错误。
所以,如果你想在循环语句中删除集合中的某个元素,就要用迭代器iterator的remove()方法,因为它的remove()方法不仅会删除元素,还会维护一个标志,用来记录目前是不是可删除状态,例如,你不能连续两次调用它的remove()方法,调用之前至少有一次next()方法的调用。
代码修改如下即可:
List<ShopGoodsEntity> list = JsonKit.parseJson2List(jsonArray, ShopGoodsEntity.class);
if (list != null && list.size() > 0) {
Iterator<ShopGoodsEntity> it = allList.iterator();
while (it.hasNext()) {
ShopGoodsEntity entity = it.next();
if (entity.getGoods_id().equals("123456")) {
it.remove();
}
}
}