zoukankan      html  css  js  c++  java
  • 在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结束后,再删除

  • 相关阅读:
    抓老鼠
    我的寒假作业
    寒假作业
    大一上学期C语言学习总结
    我的三位老师
    自我介绍
    2019春季第七周作业
    第六周总结
    第五周作业及其总结
    2019春季第四周作业
  • 原文地址:https://www.cnblogs.com/7-30-onlyone/p/11296318.html
Copyright © 2011-2022 走看看