小编典典

遍历集合,在循环中删除对象时避免 ConcurrentModificationException

all

我们都知道您不能执行以下操作,因为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

即使多个线程没有这样做。反正。

这个问题的最佳解决方案是什么?如何在不引发此异常的情况下循环从集合中删除项目?

我在Collection这里也使用了任意的,不一定是ArrayList,所以你不能依赖get.


阅读 178

收藏
2022-02-25

共1个答案

小编典典

Iterator.remove()是安全的,你可以像这样使用它:

List<String> list = new ArrayList<>();

// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
//     Iterator<String> iterator = list.iterator();
//     while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
    }
}

请注意,这Iterator.remove()是在迭代期间修改集合的唯一安全方法;如果在迭代过程中
以任何其他方式 修改了基础集合,则行为未指定。


同样,如果您有 aListIterator并且想要 添加
项目,您可以使用ListIterator#add,出于同样的原因,您可以使用Iterator#remove它,它旨在允许它。


在您的情况下,您尝试从列表中删除,但如果尝试在put一段Map时间内迭代其内容,则同样的限制适用。

2022-02-25