在List遍历删除时产生异常
解决方案:
不要使用for-each遍历,换成迭代器遍历,并且不要用list.remove()方法移除对象,用迭代器的方法iterator.remove()移除对象,具体看下面的代码:
class ArrayListDelete {
public static void main(String[] args) {
Student student = new Student("小明", "1");
Student student1 = new Student("小明", "2");
Student student2 = new Student("小明", "3");
ArrayList<Student> students = new ArrayList<>();
students.add(student);
students.add(student1);
students.add(student2);
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()){
Student next = iterator.next();
if(next.getId().equals("1")){
iterator.remove();
}
}
System.out.println(students.toString());
}
}