Collection.sort() simply sorts the list using quick sort if I recall correctly and quick sort simply does many calls to e1.compareTo(e2) where e is an element in the list.
So if you want to have a list of type MyObject and be able to sort it
List<MyObject> items = new ArrayList<>();
items.addAll(lotsOfItems);
items.sort();
Then your MyObject should implement Comparable which will allow the sorting algorithm to sort according to how you define when your object is bigger than another instance of your object.
Now whenever you call items.sort , it'll make use of your custom compareTo code, if you return 0, then you say the two objects (this and other) are the same, if you return -1, it's smaller and +1 means it's bigger.
Suppose I have an ArrayList of some objects, to sort these objects I make use of Collection.sort(list),which in turn makes use of compare to () present inside the class that implements comparable interface.
Then what for Comparator inteferace is used ?
That is correct.
By implementing Comparator, your MyObject class gets a compareTo method which you can alter, otherwise it will just use the default compareTo method that's inside every `Object`
If you want to sort your objects according to your criteria, that logic needs to go into the compareTo method that you get from implementing Comparator. So if you're sorting according to your object's id, you can do something like this:
Jan Vladimir Mostert
Idea Incubator
Collection.sort() simply sorts the list using quick sort if I recall correctly and quick sort simply does many calls to e1.compareTo(e2) where e is an element in the list.
So if you want to have a list of type MyObject and be able to sort it
List<MyObject> items = new ArrayList<>(); items.addAll(lotsOfItems); items.sort();Then your MyObject should implement
Comparablewhich will allow the sorting algorithm to sort according to how you define when your object is bigger than another instance of your object.See: docs.oracle.com/javase/6/docs/api/java/lang/Compa…
public class MyObject implements Comparable { @Override public int compareTo(MyObject other){ ... return 1 / -1 / 0 here } }Now whenever you call
items.sort, it'll make use of your customcompareTocode, if you return 0, then you say the two objects (thisandother) are the same, if you return -1, it's smaller and +1 means it's bigger.Hope it helps?