-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

prakash
  • 1
  • 2
  • google before asking question. [difference between Comparable and Comparator](http://www.javatpoint.com/difference-between-comparable-and-comparator) – afzalex Jun 22 '16 at 05:14
  • [A blog post regarding comparable and comparator](https://www.javacodegeeks.com/2013/03/difference-between-comparator-and-comparable-in-java.html) – Andrew Li Jun 22 '16 at 05:14
  • this is not for discussion, this is for solution so ask proper question please, check this http://www.programcreek.com/2011/12/examples-to-demonstrate-comparable-vs-comparator-in-java/ – Vickyexpert Jun 22 '16 at 05:16

1 Answers1

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

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115