我有一个数组列表,我想对它进行迭代。在迭代它时,我必须同时删除元素。显然,这会抛出一个java.util.ConcurrentModificationException。

处理这个问题的最佳实践是什么?我应该先克隆列表吗?

我删除的元素不是循环本身,而是代码的另一部分。

我的代码是这样的:

public class Test() {
    private ArrayList<A> abc = new ArrayList<A>();

    public void doStuff() {
        for (A a : abc) 
        a.doSomething();
    }

    public void removeA(A a) {
        abc.remove(a);
    }
}

a.doSomething可能调用Test.removeA();


当前回答

List<String> list1 = new ArrayList<>();
list1.addAll(OriginalList);

List<String> list2 = new ArrayList<>();
list2.addAll(OriginalList);

这也是一种选择。

其他回答

使用迭代器而不是数组列表

有一个集合被转换为类型匹配的迭代器

然后移动到下一个元素并删除

Iterator<Insured> itr = insuredSet.iterator();
while (itr.hasNext()) { 
    itr.next();
    itr.remove();
}

移动到下一个元素在这里很重要,因为它应该使用索引来删除元素。

这是一个例子,我使用一个不同的列表来添加对象删除,然后我使用流。Foreach从原始列表中删除元素:

private ObservableList<CustomerTableEntry> customersTableViewItems = FXCollections.observableArrayList();
...
private void removeOutdatedRowsElementsFromCustomerView()
{
    ObjectProperty<TimeStamp> currentTimestamp = new SimpleObjectProperty<>(TimeStamp.getCurrentTime());
    long diff;
    long diffSeconds;
    List<Object> objectsToRemove = new ArrayList<>();
    for(CustomerTableEntry item: customersTableViewItems) {
        diff = currentTimestamp.getValue().getTime() - item.timestamp.getValue().getTime();
        diffSeconds = diff / 1000 % 60;
        if(diffSeconds > 10) {
            // Element has been idle for too long, meaning no communication, hence remove it
            System.out.printf("- Idle element [%s] - will be removed\n", item.getUserName());
            objectsToRemove.add(item);
        }
    }
    objectsToRemove.stream().forEach(o -> customersTableViewItems.remove(o));
}

你也可以使用CopyOnWriteArrayList来代替ArrayList。这是JDK 1.5以后推荐的最新方法。

在Java 8中,你可以通过调用removeIf方法来使用Collection Interface:

yourList.removeIf((A a) -> a.value == 2);

更多信息可以在这里找到

使用流的Java 8解决方案:

        theList = theList.stream()
            .filter(element -> !shouldBeRemoved(element))
            .collect(Collectors.toList());

在Java 7中,你可以使用Guava:

        theList = FluentIterable.from(theList)
            .filter(new Predicate<String>() {
                @Override
                public boolean apply(String element) {
                    return !shouldBeRemoved(element);
                }
            })
            .toImmutableList();

注意,Guava示例的结果是一个不可变列表,这可能是也可能不是您想要的。