I have 2 ArrayList
s A
and B
of the same datastructure C
(hashCode() and equals() overridden). C represents a student's record. The two lists are of the same size and represent new student records and old ones respectively (the students are the same in both the lists, ordering might be different). I wish to keep only those records in A that have been changed. As such, I do :
A.removeAll(B)
As per the javadocs, this would take each record of A and compare with each record of B, and if it finds both equal, it will remove the record from A. If a record of A is not found to be equal to any record in B, and since all students in A are also in B, it means that that record of A has changed. The problem is that its easily of n square complexity.
Another approach can be :
Map<C> map = new HashMap<C>();
for (C record : B){
map.add(record.getStudentId(),record);
}
List<C> changedRecords = new ArrayList<C>();
for (C record : A){
if (record.equals(map.get(record.getStudentId())){
changedRecords.add(record);
}
}
I think this might be of a lower complexity than the above solution. Is that correct ?