对Vector、ArrayList在迭代的时候如果同时对其进行增删操作就会抛出java.util.ConcurrentModificationException异常
一、异常原因
代码示例
public class ConcurrentModificationException {
public static void main(String[] args) {
function2();
function1();
}
static void function1() {
Person person1 = new Person();
person1.setName("aa");
person1.setAddress("AAA");
Person person2 = new Person();
person2.setName("bb");
person2.setAddress("BBB");
ArrayList<Person> persons = new ArrayList<>();
persons.add(person1);
persons.add(person2);
System.out.println(persons.size());
for (Person person : persons) {
if ("AAA".equals(person.getAddress())) {
persons.add(new Person("cc", "CCC"));
}
persons.remove(1);
}
System.out.println(persons.size());
}
static void function2() {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(3);
System.out.println(list.size());
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer integer = iterator.next();
if (integer == 2)
list.remove(integer);
}
System.out.println(list.size());
}
}
出现此异常的原因在于ArrayList的索引发生变化
二、解决
将ArrayList换成CopyOnWriteArrayList
static void function2() {
Person person1 = new Person();
person1.setName("aa");
person1.setAddress("AAA");
Person person2 = new Person();
person2.setName("bb");
person2.setAddress("BBB");
CopyOnWriteArrayList<Person> persons = new CopyOnWriteArrayList<>();
persons.add(person1);
persons.add(person2);
System.out.println(persons.size());
for (Person person : persons) {
if ("AAA".equals(person.getAddress())) {
persons.add(new Person("cc", "CCC"));
}
persons.remove(1);
}
System.out.println(persons.size());
}