我们都知道,由于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。


当前回答

您可以像前面提到的那样直接使用迭代器,也可以保留第二个集合,并将想要删除的每个项添加到新集合中,然后在最后删除所有项。这允许您以增加内存使用和cpu时间为代价继续使用for-each循环的类型安全(应该不是一个大问题,除非您有非常非常大的列表或非常旧的计算机)

public static void main(String[] args)
{
    Collection<Integer> l = new ArrayList<Integer>();
    Collection<Integer> itemsToRemove = new ArrayList<>();
    for (int i=0; i < 10; i++) {
        l.add(Integer.of(4));
        l.add(Integer.of(5));
        l.add(Integer.of(6));
    }
    for (Integer i : l)
    {
        if (i.intValue() == 5) {
            itemsToRemove.add(i);
        }
    }

    l.removeAll(itemsToRemove);
    System.out.println(l);
}

其他回答

在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

当使用stream().map()方法迭代列表时,我最终得到了这个ConcurrentModificationException。但是,在迭代和修改列表时,for(:)没有抛出异常。

以下是代码片段,如果对任何人有帮助的话: 这里我在一个<BuildEntity>的ArrayList上迭代,并使用list.remove(obj)修改它

 for(BuildEntity build : uniqueBuildEntities){
            if(build!=null){
                if(isBuildCrashedWithErrors(build)){
                    log.info("The following build crashed with errors ,  will not be persisted -> \n{}"
                            ,build.getBuildUrl());
                    uniqueBuildEntities.remove(build);
                    if (uniqueBuildEntities.isEmpty()) return  EMPTY_LIST;
                }
            }
        }
        if(uniqueBuildEntities.size()>0) {
            dbEntries.addAll(uniqueBuildEntities);
        }

在这种情况下,一个常见的技巧是(was?)倒着走:

for(int i = l.size() - 1; i >= 0; i --) {
  if (l.get(i) == 5) {
    l.remove(i);
  }
}

也就是说,我很高兴你在Java 8中有更好的方法,例如removeIf或过滤流。

您可以像前面提到的那样直接使用迭代器,也可以保留第二个集合,并将想要删除的每个项添加到新集合中,然后在最后删除所有项。这允许您以增加内存使用和cpu时间为代价继续使用for-each循环的类型安全(应该不是一个大问题,除非您有非常非常大的列表或非常旧的计算机)

public static void main(String[] args)
{
    Collection<Integer> l = new ArrayList<Integer>();
    Collection<Integer> itemsToRemove = new ArrayList<>();
    for (int i=0; i < 10; i++) {
        l.add(Integer.of(4));
        l.add(Integer.of(5));
        l.add(Integer.of(6));
    }
    for (Integer i : l)
    {
        if (i.intValue() == 5) {
            itemsToRemove.add(i);
        }
    }

    l.removeAll(itemsToRemove);
    System.out.println(l);
}

这可能不是最好的方法,但对于大多数小的情况,这应该是可以接受的:

创建第二个空数组,只添加你想保留的数组

我不记得我从哪里读到的…为了公平起见,我会做这个维基,希望有人能找到它,或者只是为了不赢得我不应得的代表。