0

What is the difference between comparable and comparator interface and in which condition which one should use

Arvind
  • 1,548
  • 17
  • 23

2 Answers2

1

If you own sorting objects, you have a choice to implement Comapreble in them or separate logic into distinct Comparator. If you are working with third party objects and you do not want to extend them to add coparison logic, you use Comparator.

Mikhail
  • 4,175
  • 15
  • 31
1

A Comparable is the interface that defines the natural ordering of objects. For example, String implements Comparable according to the lexicographic order, and Integers implement Comparable according to the numeric order. If a class is comparable, this will be the default order to apply on its instances (e.g. in binary search, sorting or SortedMap).

A comparator defines an independent comparison mechanism, which can sometimes be an alternative to the natural ordering of elements. For example, you can use a different ordering logic for strings, and use it for sorting string arrays.

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78