遍历List的同时对List进行修改
先上代码:
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!
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 集合ArrayList遍历修改问题
- 下一篇: Android遍历数组、集合和Map