Reputation: 3331
I have two lists of Student objects. A student object is as follows:
Student
int id
int class id
String name
int age
In one list, I have student objects with the classId, name and age fields populated. I then insert them into a database which returns a collection of those same objects with the id populated with the integer assigned by the db schema. I wish to equate these two lists as best as possible to ensure the db operation was successful. I can think of two ways to do this. Either equate all student objects in the input list and output lists using all fields except id. Or, manually injecting the id of each student in the input list with the output list's values. Both ways are pretty unclean in their implementation so I was hoping there was a clean way to do it? For example, in the first option I can sort both the input and output collections, then iterate the first collection and compare with an index into the output collection for each field.
Upvotes: 2
Views: 3154
Reputation: 131
You can make your Student override the .equals(Object o)
method.
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;
}
}
Then you can compare two students like so:
Student s1 = ...;
Student s2 = ...;
if(s1.equals(s2)) {
//Do this when they are equal
}
This is a clean way to check for equality and all of Java's functions will call this overrided equals method. You can also use it with lists.
List<Student> studentList = ...;
Student s1 = ...;
if(studentList.contains(s1)) {
//Do this when s1 is in the list
}
Please let me know if you have any questions or if I misunderstood your question.
Upvotes: 1