情形:将一个表中所有具有偶数值的项删除
复制代码
1
2
3
4
5
6public static void removeEvens(List<Integer> list) { for(Integer x : list) if(x % 2 == 0) list.remove(x); }
使用增强的for循环, 不能对元素进行删除,报出ConcurrentModifictionExecption。
迭代器内部的每次遍历都会记录List内部的modcount当做预期值,然后在每次循环中用预期值与List的成员变量modCount作比较,但是普通list.remove调用的是List的remove,这时modcount++,但是iterator内记录的预期值=并没有变化,所以会报错,
复制代码
1
2
3
4
5
6
7
8
9
10
11public static void removeEvens(List<Integer> list) { Iterator<Integer> itr = list.iterator(); while(itr.hasNext()){ Integer i = (Integer) itr.next(); if(i % 2 == 0) itr.remove(); } }
但是如果在Iterator中调用remove,
正确做法:使用迭代器,以及迭代器中的remove()方法, 该方法属于迭代器的方法,所以删除之后,迭代器知道自己下一步该做什么,这时会同步List的modCount到Iterator中,故不再报错.
源自 《数据结构和算法分析描述》
最后
以上就是感动未来最近收集整理的关于增强for循环只能遍历不能增删的全部内容,更多相关增强for循环只能遍历不能增删内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复