ArrayList中找到对象后无法删除,触发ConcurrentModificationException异常
解决ArrayList遍历删除时的ConcurrentModificationException异常
你遇到的ConcurrentModificationException是因为用增强for循环(foreach)遍历ArrayList时,直接调用集合的remove()方法修改集合结构导致的。
增强for循环底层依赖ArrayList的迭代器实现,迭代器在遍历过程中会维护modCount(集合实际修改次数)和expectedModCount(迭代器预期修改次数)两个变量。当你直接调用Student_Class.remove(student)时,只会更新modCount,但迭代器的expectedModCount不会同步更新,下一次迭代调用next()时,两者不匹配就会抛出这个异常。
下面是三种可行的解决方法:
方法1:使用迭代器的remove方法
这是标准的安全遍历删除方式,迭代器自身的remove()方法会同步更新expectedModCount,彻底避免异常:
public static void DeleteStudent(ArrayList<Student> Student_Class, String studentid) { Iterator<Student> iterator = Student_Class.iterator(); while (iterator.hasNext()) { Student student = iterator.next(); if (student.getId().equalsIgnoreCase(studentid)) { iterator.remove(); break; // 只删除第一个匹配的Student就保留该行;要删除所有匹配项则移除 } } }
方法2:倒序普通for循环
倒序遍历的时候,删除当前元素不会影响前面未遍历元素的索引(后面的元素已遍历完成),同样能避免异常:
public static void DeleteStudent(ArrayList<Student> Student_Class, String studentid) { for (int i = Student_Class.size() - 1; i >= 0; i--) { Student student = Student_Class.get(i); if (student.getId().equalsIgnoreCase(studentid)) { Student_Class.remove(i); break; // 同理,删第一个保留该行,删所有则移除 } } }
方法3:Java 8+的removeIf方法
如果你的项目基于Java 8及以上版本,removeIf()是最简洁的写法,底层基于迭代器实现,安全且代码紧凑:
public static void DeleteStudent(ArrayList<Student> Student_Class, String studentid) { Student_Class.removeIf(student -> student.getId().equalsIgnoreCase(studentid)); }
内容的提问来源于stack exchange,提问作者Thomas Hutton
相关产品推荐
相关产品推荐

