当我们在程序上面运行时,只要修改了ArrayList
就会得到java.util.ConcurrentModificationException
。发生这种情况是因为ArrayList
迭代器在设计上是快速失效的。这意味着一旦创建了迭代器,如果修改了ArrayList
,则会抛出ConcurrentModificationException
。CopyOnArrayList并发修改
public class ConcurrentListExample {
public void someMethod() {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
// get the iterator
Iterator<String> it = list.iterator();
//manipulate list while iterating
while (it.hasNext()) {
String str = it.next();
System.out.println(str);
if (str.equals("2")) {
list.remove("5");
}
if (str.equals("3")) {
list.add("3 found");
}
if(str.equals("4")) {
list.set(1, "4");
}
}
}
}
,但如果我们采取Employee
类:
public class Test {
public static void main(String[] args) {
List al = new ArrayList();
Employee ee = new Employee(1, "anoj");
Employee ee1 = new Employee(2, "hai");
al.add(ee);
al.add(ee1);
Iterator it = al.iterator();
while (it.hasNext()) {
Employee hh = (Employee)it.next();
if (hh.getName().equals("anoj")) {
al.remove(0);
System.out.println(al);
}
}
}
}
我没有得到一个ConcurrentModificationException
。
其正确的“你应该添加或删除的对象,而迭代。 – Sarma
能否请您修正格式?很难看到发生了什么事情在这个代码。在第一个块,请降低缩进级别,使其不扬长而去屏幕的右侧。而在第二块,请加缩进合适的。这将使人们更容易阅读你的问题,并给出答案。 – yshavit
什么是真正的问题在这里? –