Java Concurrent Modification Exception Error

后端 未结 8 1805
庸人自扰
庸人自扰 2020-12-11 03:50

Im playing around with some code for my college course and changed a method from

public boolean removeStudent(String studentName)
{
    int index = 0;
    f         


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 04:19

    This error occurs because you are trying to alter the size of a collection while you are iterating it. If you have 10 students, you start your loop expecting to go through 10 iterations. When you remove a student, how many iterations do still need to go? The answer obviously depends on where you removed your student from the list and where you currently are in your iteation. Obviously, java cannot know this.

    To get around this, you must use an iterator. You can accomplish this as follows:

    Iterator studentsIterator;
    for(studentsIterator = students.iterator(); studentsIterator.hasNext();)
    {
        Student student = studentsIterator.next();
        if(student... /* condition */)
        {
            studentIterator.remove();  //This removes student from the collection safely
        }
    }
    

提交回复
热议问题