ArrayList

如果需要边遍历边 remove ,必须使用 iterator。且 remove 之前必须先 next,next 之后只能用一次 remove。
package com.study.lock;

import java.util.ArrayList;
import java.util.Iterator;

public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        //报错:ConcurrentModificationException
//        for (Integer integer : list) {
//            list.remove(integer);
//        }
        
        Iterator<Integer> iterator = list.iterator();
        
        //ConcurrentModificationException
//        while(iterator.hasNext()) {
//            list.remove(iterator.next());
//            System.out.println("list.size="+list.size());
//        }
        
        //报错: 通过iterator边遍历边remove元素的正确方式
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
            iterator.remove();
            System.out.println("list.size="+list.size());
        }
    }
}
list边遍历边修改

https://juejin.im/post/6844903566331609096

原文地址:https://www.cnblogs.com/yfzhou528/p/13677268.html