Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object not being removed from array after being found in array list

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

        }

    }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading