why there is two interface comparable and comparator in java for sorting the collections?
both are doing the same task it seems... confusion on this sorting technique? Please advise
why there is two interface comparable and comparator in java for sorting the collections?
both are doing the same task it seems... confusion on this sorting technique? Please advise
One might want to sort given objects in other way then the it was defined in the given object (using Comparable
), that's why there is Comparator
available.
Comparable
- used in given class to define the default/natural ordering sorting
Comparator
- used by foreign code (e.g. from different library) to sort the data in different way, or to add sorting to class that doesn't define Comparable
, or to add different sorting order (e.g. sometimes you might want to sort strings case insensitive and sometimes case sensitive).