自定义了一个简单的Student类,发现如下方法会抛出一个
java.util.ConcurrentModificationException
这是因为增强for循环实际上还是使用了List的Iterator,而Iterator是快速失败的,即在Iterator进行迭代的过程中不能改变Collection的结构,所以不能在迭代的过程中添加或者删除元素.
要避免这个问题可以使用Iterator自带的remove方法
或者重写Student的equals方法
不过后者的限制是只移除第一个符合条件的元素
java.util.ConcurrentModificationException
List<Student> studentList = new ArrayList<Student>();
Student s = new Student();
s.setId(1);
s.setName("student1");
studentList.add(s);
s = new Student();
s.setId(2);
s.setName("student2");
studentList.add(s);
s = new Student();
s.setId(3);
s.setName("student3");
studentList.add(s);
for (Student student : studentList) {
if (student.getId().equals(1)) {
studentList.remove(s);
}
}
这是因为增强for循环实际上还是使用了List的Iterator,而Iterator是快速失败的,即在Iterator进行迭代的过程中不能改变Collection的结构,所以不能在迭代的过程中添加或者删除元素.
要避免这个问题可以使用Iterator自带的remove方法
Iterator<Student> iterator = studentList.iterator();
while (iterator.hasNext()) {
if (iterator.next().getId().equals(id)) {
iterator.remove();
}
}
或者重写Student的equals方法
Student studentToDelete = new Student();
studentToDelete.setId(1);
studentList.remove(studentToDelete);
不过后者的限制是只移除第一个符合条件的元素