遍历List的同时对List进行修改
来源:互联网 发布:什么是java反射机制 编辑:程序博客网 时间:2024/06/08 16:24
先上代码:
Collection<String> list = new ArrayList<String>(); list.add("Android"); list.add("iPhone"); list.add("Windows Mobile"); // example 0 Iterator<String> itr0 = list.iterator(); while(itr0.hasNext()){ String lang = itr0.next(); itr0.remove(); } // example 1 Iterator<String> itr1 = list.iterator(); while(itr1.hasNext()){ String lang = itr1.next(); list.remove(lang); } // example 2 for(int i = 0; i < list.size(); i++){ list.remove(i); } // example 3 for(String language: list){ list.remove(language); }
example0,example2不会抛出ConcurrentModificationException异常;但example1,example3则会抛出ConcurrentModificationException异常;
原因分析:
example1没调用Iterator的remove方法进行删除;在itr1.next()中会检查
ourList.modCount != expectedModCount则抛出ConcurrentModificationException异常;
@SuppressWarnings("unchecked") public E next() { ArrayList<E> ourList = ArrayList.this; int rem = remaining; if (ourList.modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (rem == 0) { throw new NoSuchElementException(); } remaining = rem - 1; return (E) ourList.array[removalIndex = ourList.size - rem]; }
example3的for-each循环内部其实也是使用了Iterator来遍历Collection,它也调用了Iterator.next(),这同样也会检查(元素的)变化并抛出ConcurrentModificationException!
0 0
- 遍历List的同时对List进行修改
- C#对List同时遍历删除操作
- cforeach同时遍历两个List的方法
- 在遍历List时,对List里的对象进行remove(),此操作会改变List的大小()
- list 判断里面判断存不存在元素 如果遍历的同时会修改 就用 ListIterator
- 同时遍历 2个List
- 遍历List 同时 remove 元素
- 遍历List 同时 remove 元素
- python同时遍历两个list
- c:forEach中对List的遍历
- 对List的遍历有三种方式
- 对list进行分页
- 对list进行排序
- 对list进行排序
- 对list进行切片
- 对list进行排序
- 对list进行排序
- 对list进行分类
- zoj3119 DP
- XML schema学习的部分总结
- lightoj1048 Conquering Keokradong
- 不用加减乘除实现加法
- JavaMail1.5.4 源码
- 遍历List的同时对List进行修改
- 主题制作
- ubuntu下使用ssh挂载服务器
- Git 托管文件至GitHub
- Python计算机视觉编程练习8:string 模块学习
- iOS通过CLLocationManager调用地图导航功能
- 敏捷开发流程(转)
- jdbc学习
- [转载] cell重绘