Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Concurrent Modification Exception Error

Tags:

java

arraylist

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

public boolean removeStudent(String studentName)
{
    int index = 0;
    for (Student student : students)
    {
        if (studentName.equalsIgnoreCasee(student.getName()))
        {
            students.remove(index);
            return true;
        }
        index++;
    }
    return false;
}

To:

public void removeStudent(String studentName) throws StudentNotFoundException
{
    int index = 0;
    for (Student student : students)
    {
        if (studentName.equalsIgnoreCase(student.getName()))
        {
            students.remove(index);
        }
        index++;
    }
    throw new  StudentNotFoundException( "No such student " + studentName);
}

But the new method keeps giving a Concurrent Modification error. How can I get round this and why is it happening?

like image 233
ToniHopkins Avatar asked Mar 13 '13 11:03

ToniHopkins


1 Answers

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<Student> it = students.iterator();
    while (it.hasNext()) {
        Student student = it.next();

        if (studentName.equalsIgnoreCase(student.getName())) {
                it.remove();
                return true;
        }
    }
    return false;
like image 81
Eyal Schneider Avatar answered Oct 07 '22 04:10

Eyal Schneider