Hi guys,
I am having an issue finding duplicates in an arrayList.
Here is some code
studentRecords.add(new Student("Jo", "Pip", "JP000", LocalDate.of(1999,9,23), Sex.FEMALE));
studentRecords.add(new Student("Tara", "Bot", "TB345", LocalDate.of(1991,9,1), Sex.FEMALE));
studentRecords.add(new Student("Mara", "Lewart", "ML456", LocalDate.of(1988,5,23), Sex.FEMALE));
studentRecords.add(new Student("Anna", "Clarke", "AC010", LocalDate.of(1999,1,1), Sex.FEMALE));
studentRecords.add(new Student("Frank", "Boia", "FB300", LocalDate.of(2001,8,13), Sex.MALE));
studentRecords.add(new Student("Anna", "Clarke", "AC010", LocalDate.of(1999,1,1), Sex.FEMALE));
studentRecords.add(new Student("Jo", "Pip", "JP000", LocalDate.of(1999,9,23), Sex.FEMALE));
This is the list of student records stored in an ArrayList.
I have to make sure that I identify the duplicates and store the duplicates in another arrayList, duplicateRecords for the sake of argument.
Now, the first thing I tried was to do something like this
public void findDuplicates() {
if(!studentRecords.isEmpty()) {
duplicateRecords = new ArrayList<Student>();
for(int i = 0; i < studentRecords.size(); i++) {
for(int j = 1; j < studentRecords.size(); j++) {
if(studentRecords.get(i).equals(studentRecords.get(j)) && i != j) {
duplicateRecords.add(studentRecords.get(i));
}
}
}
}
printDetails(studentRecords);
System.out.println("############");
printDetails(duplicateRecords);
}
Which is buggy because, of course, it adds the record for Anna twice. I guess the complexity comes in if there are multiple duplicates, for example what happens if there are 3 records for Anna Clarke? In theory I'd want that to be twice in the duplicateRecords because it is a double duplicate
I can't really think of another approach though, any ideas?