Java Concurrent Modification Exception Error

后端 未结 8 1763
庸人自扰
庸人自扰 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:20

    You are not allowed to remove an element from your collection while you iterate over it. The iterator detects a structural change during its usage, and throws the exception. Many collections are implemented in such a way.

    Use the iterator directly instead:

        Iterator it = students.iterator();
        while (it.hasNext()) {
            Student student = it.next();
    
            if (studentName.equalsIgnoreCase(student.getName())) {
                    it.remove();
                    return true;
            }
        }
        return false;
    

提交回复
热议问题