I have a method to delete an object from an array list based on an attribute of the class called id. When I call it, it finds the correct id then breaks. This is all very new to me
public static void DeleteStudent(ArrayList<Student> Student_Class, String studentid) {
for(Student student : Student_Class)
if(student.getId().equalsIgnoreCase(studentid))
Student_Class.remove(student);
}
error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
at StudentProgram.DeleteStudent(StudentProgram.java:39)
at StudentProgram.main(StudentProgram.java:28)
>Solution :
Only use a for-each loop if you are doing READ-ONLY operations on a Collection
(your ArrayList
is a Collection
).
If you want to modify while looping, you should use a java.util.Iterator
instead.
An Iterator
is easy to use, and your ArrayList
even gives you a method to fetch an Iterator
. All you have to do is add an import on the top (import java.util.Iterator;
), then say Iterator<Student> iterator = myList.iterator();
.
Here is how it would be done with your code example. Don’t forget to include the import at the top of your class.
public static void DeleteStudent(ArrayList<Student> Student_Class, String studentid)
{
Iterator<Student> iterator = Student_Class.iterator();
while(iterator.hasNext())
{
Student student = iterator.next();
if(student.getId().equalsIgnoreCase(studentid))
{
iterator.remove(); //removes the most recently fetched student
}
}
}