首先这个是不成立的
public class Test {
public static void main(String[] args) {
//原List集合
List<Student> list = new ArrayList(){{
Student student = new Student();
student.setId(1);
Student student2 = new Student();
student2.setId(2);
Student student3 = new Student();
student3.setId(3);
add(student);
add(student2);
add(student3);
}};
//模拟遍历时自身操作
for (Student student : list) {
//如果 id为2就把他添加到list
if (student.getId() == 2){
list.add(student);
//list.remove(student);
}
}
//最后的结果
System.out.println(list);
}
}
结果:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at com.dcq.Test.main(Test.java:24)
目前能力有限讲不出所以然,暂时记住在遍历的时候不能对其本身进行操作。
↓↓↓可参考下方大佬的文章↓↓↓
nConcurrentModificationException异常原因和解决方法_碌碌无为_心不在烟的博客-CSDN博客_concurrentmodificationexception