Java,如何搜索保存在数组列表中的对象的特定变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7931527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:03:50  来源:igfitidea点击:

Java, how do I search a specific variable of Objects saved in a array list

javasearcharraylist

提问by vedran

I have a Personnel class, where I store all of Objects of type student, professor, tutor...

我有一个 Personnel 类,在那里我存储了所有类型为学生、教授、导师的对象......

class Personnel {
     ArrayList<Student> activeStudentsList = new ArrayList<Student>();
}

and I have a class Student

我有一个班级学生

class Student extends Person {
    public Student (String studentID, String firstName, String lastName) {
        super(firstName, lastName);
        this.studentID = studentID;
    }
}

Now, what I want to do before adding a student into array list, is to check if he's already there. I was using this:

现在,在将学生添加到数组列表之前我想做的是检查他是否已经在那里。我正在使用这个:

private boolean isStudentActive(String studentID) {
    if (activeStudentsList.contains(studentID)) {
        System.out.println("The student " + studentID + " is already on the list.");
        return true;
    } else
        return false; 
}

The problem is, my array list is ArrayList<Student>, so I can't search for a specific String (studentID). How do I do this? How do I only search String studentIDof each object on the list? EDIT: (Is there somethin like activeStudentsList.studentID.contains(studentID)?)

问题是,我的数组列表是ArrayList<Student>,所以我无法搜索特定的字符串 ( studentID)。我该怎么做呢?如何只搜索studentID列表中每个对象的字符串?编辑:(有类似的东西activeStudentsList.studentID.contains(studentID)吗?)

回答by Bhesh Gurung

Your Studentneeds to implement the equalsand hashCodeproperly and you can just use List.contains.

Student需要正确实施equalshashCode,您只需使用List.contains.

回答by JB Nizet

Iterate through the list, test if the current student's ID is equal to the one you're looking for. If yes, return true, else continue. At the end of the iteration, return false.

遍历列表,测试当前学生的 ID 是否与您要查找的 ID 相同。如果是,返回真,否则继续。在迭代结束时,返回 false。

Or, if you want something easier and faster, use a Map<String, Student>instead of the list, storing the students indexed by their ID. You may use a HashMap, or LinkedHashMap if you need to preserve the insertion order like a List does.

或者,如果您想要更简单快捷的操作,请使用 aMap<String, Student>而不是列表,存储按学生 ID 索引的学生。如果您需要像 List 那样保留插入顺序,您可以使用 HashMap 或 LinkedHashMap。

回答by Java Drinker

A very simplistic implementation based on Bhesh's mention of making equals and hashcode use the student id:

基于 Bhesh 提到的使 equals 和 hashcode 使用学生 ID 的一个非常简单的实现:

class Student extends Person {

    private String studentID;

    public Student (String studentID, String firstName, String lastName) {
        super(firstName, lastName);
        this.studentID = studentID;
    }

    @Override
    public boolean equals(Object object) {
        if(object instanceof Student) {
            Student s = (Student) object;
            return this.studentID.equals(s.studentID);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return studentID.hashCode();
    }
}

回答by Wizetux

Assuming that the studentID string is public or that you have a public Get method for it, you can use the Java For-each loop to check each element in the list:

假设 studentID 字符串是公开的或者您有一个公开的 Get 方法,您可以使用 Java For-each 循环来检查列表中的每个元素:

for (Student s : activeStudentsList)
{
   if (s.studentID == studentID)
      return true;
}
return false;

回答by charly's

Enjoy your time and take the time to use Guava libraries : http://code.google.com/p/guava-libraries/.

享受您的时间并花时间使用 Guava 库:http: //code.google.com/p/guava-libraries/

try
        {
            Person item = Iterables.find(this.personList,
                    new Predicate<Person>() {
                        public boolean apply(Person q)
                        {
                            return itemId.equals(q.getId());
                        }
                    });
            return item;
        } catch (NoSuchElementException exception)
        {
            return null;
        }

回答by Steve J

OK, here's my version. Avoid loops and terminating conditions and whatnot, and just program functionally using Google's Guava methods:

好的,这是我的版本。避免循环和终止条件等,只需使用 Google 的 Guava 方法进行功能性编程:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.TreeMultimap;

public class TestClass {

    class Person {
        private String firtName = null;
        private String lastName = null;

        public Person(String firtName, String lastName) {
            super();
            this.firtName = firtName;
            this.lastName = lastName;
        }
    };

    class Student extends Person {
        private String studentID = null;

        public Student(String studentID, String firstName, String lastName) {
            super(firstName, lastName);
            this.studentID = studentID;
        }

        public String getStudentID() {
            return studentID;
        }
    }

    class Personnel {
        ArrayList<Student> activeStudentsList = new ArrayList<Student>();

        public boolean isStudentActive(final String studentID) {
            return Iterables.size(Iterables.filter(activeStudentsList,
                    new Predicate<Student>() {
                        @Override
                        public boolean apply(Student arg0) {
                            return arg0.getStudentID().equals(studentID);
                        }
                    })) == 1;
        }
    }

}

It might seem a bit top-heavy for this sort of search, but I find using Filters and Transforms very useful in more complicated scenarios.

对于这种搜索来说,它可能看起来有点头重脚轻,但我发现在更复杂的场景中使用过滤器和转换非常有用。