在foreach循环中使用remove报ConcurrentModificationException异常原因

在foreach循环中使用remove报ConcurrentModificationException异常原因

我的代码具体是这样的

   int dindex=0;
                    int did=getInt("请输入需要删除的学生学号:");
                    for (Student student:list) {
                        if(student.id==did){
                            list.remove(student);
                        }
                    }

这样会导致remove后,导致list在循环中下标和实际已经被修改后的下标不一致

我自己的解决方案是:

int dindex=-1;
                    int did=getInt("请输入需要删除的学生学号:");
                    for (Student student:list) {
                        if(student.id==did){
                            dindex=list.indexOf(student);
                        }
                    }
                    if(dindex!=-1)
                        list.remove(dindex);
                    else
                        System.out.println("没有此学生");

记录下标 不改变list本身 等foreach结束后,再删除

猜你喜欢

转载自www.cnblogs.com/7-30-onlyone/p/11296318.html
今日推荐