0

I am writing a program to keep track a school's classes and students. I have School, Classroom, and Student objects. The school contains an ArrayList of classroom objects and each classroom contains an ArrayList of student objects.

I am trying to write a method in the School class to remove a student using a String name and String classroomName as a parameter.

This is what I have so far:

public void remove( String studentName, String classroomName) {
    for(Classroom c : classes) {
        if(c.className.equals(classroomName)){
         //search for student and remove
          for(Student s : students){
             if(s.studentName.equals(studentName)){
                s.remove(studentName);
        }
      }
    }
}

I think this is not working because the ArrayList of Student objects is declared in the Classroom class.

Is there a way to search through an object ArrayList for an element using a non object parameter?

rrfeva
  • 77
  • 1
  • 5
  • 4
    You cannot remove element of a list while iterating on it (except if you explicitly use an iterator). See: https://stackoverflow.com/questions/49668278/how-can-i-remove-an-element-in-a-string-list-in-java/49668440#49668440 – Arnaud Denoyelle Sep 18 '18 at 15:37
  • Can you do `c.students` in nested loop? Also, don;t concurrently alter a collection while you are iterating over it. – nabster Sep 18 '18 at 15:37
  • Possible duplicate of : https://stackoverflow.com/questions/10431981/remove-elements-from-collection-while-iterating – dbl Sep 18 '18 at 15:38
  • 1
    Apart from that, you don't want to replace `studentName` from `student` (in the inner for loop). You actually want to replace `s` from `students`. – Arnaud Denoyelle Sep 18 '18 at 15:39

2 Answers2

1

Like they told you, you can't remove an element from a list while iterating on it unless you use an iterator or you manually control the iteration with indexes.

Otherwise, if you're using Java 8 you can go with:

students.removeIf(s -> s.studentName.equals(studentName));
samugi
  • 395
  • 5
  • 17
0

As others have noted, you can only remove elements with an Iterator. You want something like this:

    for(Iterator<Student> it = c.students.iterator(); it.hasNext();)
    {
        Student s = it.next();
        if(s.studentName.equals(studentName))
            it.remove();
    }

You say that each Classroom contains a List of Students, so I'm assuming c.students is what you want to iterate over - your posted code uses a standalone list students. Maybe that's a typo?

RaffleBuffle
  • 5,396
  • 1
  • 9
  • 16