我有一个数组列表,我想对它进行迭代。在迭代它时,我必须同时删除元素。显然,这会抛出一个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();


当前回答

关于

import java.util.Collections;

List<A> abc = Collections.synchronizedList(new ArrayList<>());

其他回答

有时候守旧是最好的。只需要一个简单的for循环,但要确保从列表的末尾开始,否则当你删除项目时,你会与索引不同步。

List<String> list = new ArrayList<>();
for (int i = list.size() - 1; i >= 0; i--) {
  if ("removeMe".equals(list.get(i))) {
    list.remove(i);
  }
}
for (A a : new ArrayList<>(abc)) {
    a.doSomething();
    abc.remove(a);
}

只需在ArrayList.remove(a)语句后添加一个断点

在迭代列表时,如果您想删除元素是可能的。让我们看看下面的例子,

ArrayList<String>  names = new ArrayList<String>();
        names.add("abc");
        names.add("def");
        names.add("ghi");
        names.add("xyz");

我有上述名称的数组列表。我想从上面的列表中删除“def”名称,

for(String name : names){
    if(name.equals("def")){
        names.remove("def");
    }
}

上面的代码抛出ConcurrentModificationException异常,因为您在迭代时修改了列表。

因此,要从数组列表中删除def名称,

Iterator<String> itr = names.iterator();            
while(itr.hasNext()){
    String name = itr.next();
    if(name.equals("def")){
        itr.remove();
    }
}

上面的代码,通过迭代器,我们可以从数组列表中删除“def”名称,并尝试打印数组,你会看到下面的输出。

输出:[abc, ghi, xyz]

错误

有一个错误,当我添加到相同的列表从我获取元素:

fun <T> MutableList<T>.mathList(_fun: (T) -> T): MutableList<T> {
    for (i in this) {
        this.add(_fun(i))   <---   ERROR
    }
    return this   <--- ERROR
}

决定

工作时添加到一个新的列表:

fun <T> MutableList<T>.mathList(_fun: (T) -> T): MutableList<T> {
    val newList = mutableListOf<T>()   <---   DECISION
    for (i in this) {
        newList.add(_fun(i))   <---   DECISION
    }
    return newList   <---   DECISION
}