Collection.sort() work in Java? Comparable and Comparator play in sorting? Collection.sort() in my program?I am having tough time understanding above concepts. Please help me in understanding these concepts.If possible give examples.
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?