Java Concurrent Modification Exception Error

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

    You are not allowed to remove an element from students collection while iterating through it.

    This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

    For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.

    http://docs.oracle.com/javase/6/docs/api/java/util/ConcurrentModificationException.html

    Try changing to

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

提交回复
热议问题