一边遍历ArrayList一边删除当前元素会引发java.util.ConcurrentModificationException
即“要确保遍历过程顺利完成,必须保证遍历过程中不更改集合的内容(Iterator的remove()方法除外),因此,确保遍历可靠的原则是只在一个线程中使用这个集合,或者在多线程中对遍历代码进行同步。”
参考文章:http://gceclub.sun.com.cn/yuanchuang/week-14/iterator.html
import java.util.ArrayList;public class RetrieveAndRemove { public static void main(String[] args){ ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); for(Integer i : list) list.remove(i); // Exception in thread "main" java.util.ConcurrentModificationException } }
解决方法1:
使用java.util.Iterator
for(Iterator it = list.iterator(); it.hasNext();){ Integer i = (Integer)it.next(); it.remove();}
解决方法2:
java.util.concurrent包中的集合类