简体   繁体   中英

How to search for an element in an ArrayList using a string?

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?

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));

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM