当我们运行上面的程序时,我们会java.util.ConcurrentModificationException
立即得到ArrayList
修改。发生这种情况是因为ArrayList
迭代器在设计上是快速失败的。这意味着一旦迭代器被创建,如果ArrayList
被修改,它会抛出一个ConcurrentModificationException
.
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
.