I have a arraylist called memberList that holds member objects. I want to sort and compare different types of member objects from the arraylist by calling the member.calculateCost() method.
I need to use the Collections.sort(memberList, myComparatorObject). I already have my compare(Object o, Object o2) method. I dont understand the 2nd parameter “myComparatorObject” in Collections.Sort(). What is the myComparatorObject?
The first argument is the list which need to be sorted
The second argument is the object of class implementing Comparator interface. This will determine the ordering of the elements in your list.
you can use this too “sort(List<T> list)”, but in that case the elements of the list should be comparable, i.e. they should implement Comparable interface and their comparison done by compareTo method should not throw ClassCastException
myComparatorObject holds the sorting logic for your member list. you need to override hascode(), equals() method with your sort logic.
suppoes, you member list has member id to sort by id you have to write the sort logic in equals method and hashcode which checks equality to return the id or your custom has code generated from id