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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With