List删除元素

记性不好

List<Group> groupList = groupDao.findByParentIdAndFlag(2l,0);
if (groupList.size() > 0){
Iterator it = groupList.iterator();
while(it.hasNext()){
Group group = (Group) it.next();
if (group.getId().equals(793l)) {
it.remove(); //移除该对象
}
}
}

误区:

如果将上例中的iterator.remove(); 改为list.remove(student);将会报ConcurrentModificationException异常。

这是因为:使用迭代器遍历,却使用集合的方法删除元素的结果。

再说for循环:

总体来说,不建议使用高级for循环(增强for循环)遍历删除/增加操作。

原因就是可能会报ConcurrentModificationException异常。

说可能是比较准确的,可能会报,也可能不报。

原文地址:https://www.cnblogs.com/michaelcnblogs/p/13266189.html