Create a comparator:
public class CarComparator implements Comparator<Car>
{
public int compare(Car c1, Car c2)
{
return c1.carName.compareTo(c2.carName);
}
}
Now add all the cars of the ArrayList
to a SortedSet
, preferably TreeSet
; if there are duplicates add to the list of duplicates:
List<Car> duplicates = new ArrayList<Car>();
Set<Car> carSet = new TreeSet<Car>(new CarComparator());
for(Car c : originalCarList)
{
if(!carSet.add(c))
{
duplicates.add(c);
}
}
Finally in your duplicates
you will have all the duplicates.