简体   繁体   English

如何使用字符串在ArrayList中搜索元素?

[英]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. 学校包含教室对象的ArrayList,每个教室包含学生对象的ArrayList。

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. 我正在尝试在School类中编写一种方法,以使用字符串名称和字符串教室名称作为参数来删除学生。

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. 我认为这不起作用,因为在Classroom类中声明了Student对象的ArrayList。

Is there a way to search through an object ArrayList for an element using a non object parameter? 有没有一种方法可以使用非对象参数在对象ArrayList中搜索元素?

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: 否则,如果您使用的是Java 8,则可以使用:

students.removeIf(s -> s.studentName.equals(studentName));

As others have noted, you can only remove elements with an Iterator . 正如其他人指出的那样,您只能使用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 . 您说每个Classroom包含一个Students名单,所以我假设c.students是您要迭代的对象-您发布的代码使用了一个独立的students名单。 Maybe that's a typo? 也许是错字?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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