我们都知道,由于ConcurrentModificationException异常,您不能执行以下操作:

for (Object i : l) {
    if (condition(i)) {
        l.remove(i);
    }
}

但这显然有时有效,但并非总是如此。下面是一些特定的代码:

public static void main(String[] args) {
    Collection<Integer> l = new ArrayList<>();

    for (int i = 0; i < 10; ++i) {
        l.add(4);
        l.add(5);
        l.add(6);
    }

    for (int i : l) {
        if (i == 5) {
            l.remove(i);
        }
    }

    System.out.println(l);
}

当然,这会导致:

Exception in thread "main" java.util.ConcurrentModificationException

即使多线程没有这样做。无论如何。

这个问题的最佳解决方案是什么?如何在循环中从集合中删除项而不抛出此异常?

这里我也用了一个任意的集合,不一定是数组列表,所以你不能依赖get。


当前回答

线程安全集合修改示例:

public class Example {
    private final List<String> queue = Collections.synchronizedList(new ArrayList<String>());

    public void removeFromQueue() {
        synchronized (queue) {
            Iterator<String> iterator = queue.iterator();
            String string = iterator.next();
            if (string.isEmpty()) {
                iterator.remove();
            }
        }
    }
}

其他回答

因为问题已经回答即最好的方式是使用迭代器对象的删除方法,我想去的地方的细节java.util错误”。引发ConcurrentModificationException”。

每个集合类都有一个实现Iterator接口的私有类,并提供next()、remove()和hasNext()等方法。

接下来的代码看起来像这样…

public E next() {
    checkForComodification();
    try {
        E next = get(cursor);
        lastRet = cursor++;
        return next;
    } catch(IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
    }
}

这里checkForComodification方法实现为

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

因此,如您所见,如果您显式地试图从集合中删除一个元素。它导致modCount与expectedModCount不同,导致异常ConcurrentModificationException。

一种解决方案是旋转列表并删除第一个元素,以避免ConcurrentModificationException或IndexOutOfBoundsException

int n = list.size();
for(int j=0;j<n;j++){
    //you can also put a condition before remove
    list.remove(0);
    Collections.rotate(list, 1);
}
Collections.rotate(list, -1);

如此:

Iterator<Integer> iter = l.iterator();
while (iter.hasNext()) {
    if (iter.next() == 5) {
        iter.remove();
    }
}

我认为由于foreach循环是迭代的语法糖,使用迭代器不会有帮助…但是它给了你这个。remove()功能。

在case ArrayList:remove(int index)- if(index是最后一个元素的位置)它会避免没有System.arraycopy(),并且不会花费时间。

Arraycopy时间增加如果(索引减少),顺便说一下列表的元素也减少!

最有效的删除方法是-按降序删除其元素: 而(list.size () > 0) list.remove (list.size() 1); / /需要O (1) 而(list.size () > 0) list.remove(0); / /需要O(阶乘(n))

//region prepare data
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Integer> toRemove = new ArrayList<Integer>();
Random rdm = new Random();
long millis;
for (int i = 0; i < 100000; i++) {
    Integer integer = rdm.nextInt();
    ints.add(integer);
}
ArrayList<Integer> intsForIndex = new ArrayList<Integer>(ints);
ArrayList<Integer> intsDescIndex = new ArrayList<Integer>(ints);
ArrayList<Integer> intsIterator = new ArrayList<Integer>(ints);
//endregion

// region for index
millis = System.currentTimeMillis();
for (int i = 0; i < intsForIndex.size(); i++) 
   if (intsForIndex.get(i) % 2 == 0) intsForIndex.remove(i--);
System.out.println(System.currentTimeMillis() - millis);
// endregion

// region for index desc
millis = System.currentTimeMillis();
for (int i = intsDescIndex.size() - 1; i >= 0; i--) 
   if (intsDescIndex.get(i) % 2 == 0) intsDescIndex.remove(i);
System.out.println(System.currentTimeMillis() - millis);
//endregion

// region iterator
millis = System.currentTimeMillis();
for (Iterator<Integer> iterator = intsIterator.iterator(); iterator.hasNext(); )
    if (iterator.next() % 2 == 0) iterator.remove();
System.out.println(System.currentTimeMillis() - millis);
//endregion

索引循环:1090毫秒 对于desc指数:519毫秒-最好的 对于迭代器:1043 msec

I know this question assumes just a Collection, and not more specifically any List. But for those reading this question who are indeed working with a List reference, you can avoid ConcurrentModificationException with a while-loop (while modifying within it) instead if you want to avoid Iterator (either if you want to avoid it in general, or avoid it specifically to achieve a looping order different from start-to-end stopping at each element [which I believe is the only order Iterator itself can do]):

*更新:参见下面的注释,说明类似的情况也可以用传统的for循环实现。

final List<Integer> list = new ArrayList<>();
for(int i = 0; i < 10; ++i){
    list.add(i);
}

int i = 1;
while(i < list.size()){
    if(list.get(i) % 2 == 0){
        list.remove(i++);

    } else {
        i += 2;
    }
}

该代码中没有ConcurrentModificationException。

在这里,我们看到循环没有从开始处开始,也没有在每个元素处停止(我相信Iterator本身不能做到这一点)。

在FWIW中,我们还看到get在list上被调用,如果它的引用只是Collection(而不是更具体的list类型的Collection),则无法做到这一点——list接口包括get,但Collection接口不包括。如果不是因为这个区别,那么列表引用可以是一个集合[因此从技术上讲,这个答案将是一个直接答案,而不是一个切向答案]。

FWIWW相同的代码在修改为start at beginning at stop at每个元素后仍然有效(就像Iterator order一样):

final List<Integer> list = new ArrayList<>();
for(int i = 0; i < 10; ++i){
    list.add(i);
}

int i = 0;
while(i < list.size()){
    if(list.get(i) % 2 == 0){
        list.remove(i);

    } else {
        ++i;
    }
}