-4

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

3

1 Answer 1

0

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.