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?

4
  • 4
    You cannot remove element of a list while iterating on it (except if you explicitly use an iterator). See: stackoverflow.com/questions/49668278/… Commented Sep 18, 2018 at 15:37
  • Can you do c.students in nested loop? Also, don;t concurrently alter a collection while you are iterating over it. Commented Sep 18, 2018 at 15:37
  • Possible duplicate of : stackoverflow.com/questions/10431981/… Commented Sep 18, 2018 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. Commented Sep 18, 2018 at 15:39

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

1 Comment

you would need to do a filter on classes to get the students.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.