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:
@Override
public int compareTo(MyObject other){
if (this.id == other.id) {
return 0;
} else if (this.id > other.id) {
return 1;
} else {
return -1;
}
}
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?