按对象字段比较两个列表

时间:2016-09-23 03:49:12

标签: java

我有两个Student对象列表。学生对象如下:

Student
int id
int class id
String name
int age

在一个列表中,我有学生对象,其中填充了classId,name和age字段。然后,我将它们插入到一个数据库中,该数据库返回这些相同对象的集合,其id填充了db模式指定的整数。我希望尽可能地将这两个列表等同,以确保db操作成功。我可以想到两种方法来做到这一点。使用除id之外的所有字段将输入列表和输出列表中的所有学生对象等同。或者,使用输出列表的值手动注入输入列表中每个学生的id。两种方式在实施时都非常不干净,所以我希望有一种干净的方法可以做到这一点?例如,在第一个选项中,我可以对输入和输出集合进行排序,然后迭代第一个集合,并将索引与每个字段的输出集合进行比较。

1 个答案:

答案 0 :(得分:1)

您可以让学生覆盖.equals(Object o)方法。

public class Student {

    private int id;
    private int classId;
    private String name;
    private int age;

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (classId != other.classId)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }


}

然后你可以比较两个学生:

Student s1 = ...;
Student s2 = ...;

if(s1.equals(s2)) {
   //Do this when they are equal
}

这是一种检查相等性的简洁方法,所有Java函数都会调用这个覆盖的equals方法。您也可以将它与列表一起使用。

List<Student> studentList = ...;
Student s1 = ...;

if(studentList.contains(s1)) {
   //Do this when s1 is in the list
}

如果您有任何疑问或我误解了您的问题,请告诉我。

相关问题