-8

My questions is basically divided into two sub-questions:

  1. Comparable talks about natural ordering. Who is stopping us from implementing a non-natural ordering login in the compareTo method ?

  2. Comparator can do the same stuff as Comparable (ASC or DESC sort). So the only reason it exists is because that if we have a third party class which we cannot change (make it implement Comparable) then we can externalise the sorting logic using Comparator. Is this correct ?

deepak
  • 339
  • 6
  • 16
  • 1
    "Who is stopping us from implementing a non-natural ordering login in the compareTo method ?" Nobody. You just shouldn't then expect code which uses your `Comparable` to work correctly. And people using your class will be annoyed if it doesn't work as they contractually expect. – Andy Turner Apr 02 '17 at 15:34
  • 1
    So I'm guessing all collections of data should have one and only one way to sort them. – Hovercraft Full Of Eels Apr 02 '17 at 15:35
  • What if you want to support one class in multiple ways (say by name and by age depending on some user selected criteria)? – Elliott Frisch Apr 02 '17 at 15:35
  • "Is this correct ?" No. It doesn't have to be a third-party object that you can't change. It can simply be any class without a natural ordering. – Andy Turner Apr 02 '17 at 15:35
  • @AndyTurner Ty. So this would mean the Clients expect Comparable to sort naturally but when they want to use Comparator they must be aware of the sorting logic defined inside it ? – deepak Apr 02 '17 at 15:52
  • No, @deepak, programmers must be aware of the documented comparison logic for _both_ `compareTo` and `compare`. How else would one know what "sort naturally" means? – Lew Bloch Apr 02 '17 at 17:45
  • @LewBloch Thx. I thought naturally sort always meant ascending order. I referred this: [link]http://stackoverflow.com/questions/5167928/what-is-natural-ordering-when-we-talk-about-sorting – deepak Apr 03 '17 at 00:00
  • The "natural order" (not "natural sort") is either ascending or descending depending on the direction in which you traverse it. But what defines "ascending", hm? Why, the comparison of "less than", "equal to", or "greater than", of course. And what defines the comparison? Why, the comparison operation, of course. And which comparison operation? Why the one defined (defined!) by either the `Comparable#compareTo` implementation, which is the "natural order" by definition, or an implementation of `Comparator#compare`, which by definition is, you guessed it!, not the "natural order". – Lew Bloch Apr 03 '17 at 00:44
  • This is in the Javadocs for these types, which I commend to your attention. – Lew Bloch Apr 03 '17 at 00:47

1 Answers1

3

A class can only have one compareTo method but you can define as many comparators as you like for it. This is useful to define different orderings which is not such an uncommon requirement.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45