码迷,mamicode.com
首页 > 其他好文 > 详细

List删除元素

时间:2020-07-08 13:33:38      阅读:47      评论:0      收藏:0      [点我收藏+]

标签:迭代   增强for循环   for循环   exception   parent   list   ext   对象   except   

记性不好

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异常。

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

List删除元素

标签:迭代   增强for循环   for循环   exception   parent   list   ext   对象   except   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!