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


当前回答

最好的方法(推荐)是使用java.util.concurrent包。通过 使用这个包可以很容易地避免这种异常。请参考 修改代码:

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

其他回答

你也可以使用递归

java中的递归是一个方法连续调用自身的过程。java中调用自身的方法称为递归方法。

对于上述问题,我有一个建议。不需要辅助列表或任何额外的时间。请找到一个例子,它会做同样的事情,但以不同的方式。

//"list" is ArrayList<Object>
//"state" is some boolean variable, which when set to true, Object will be removed from the list
int index = 0;
while(index < list.size()) {
    Object r = list.get(index);
    if( state ) {
        list.remove(index);
        index = 0;
        continue;
    }
    index += 1;
}

这将避免并发异常。

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

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

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

ConcurrentHashMap或ConcurrentLinkedQueue或ConcurrentSkipListMap可能是另一个选项,因为它们永远不会抛出任何ConcurrentModificationException,即使您删除或添加项目。

ListIterator允许您在列表中添加或删除项目。假设你有一个Car对象列表:

List<Car> cars = ArrayList<>();
// add cars here...

for (ListIterator<Car> carIterator = cars.listIterator();  carIterator.hasNext(); )
{
   if (<some-condition>)
   { 
      carIterator().remove()
   }
   else if (<some-other-condition>)
   { 
      carIterator().add(aNewCar);
   }
}