0

In short the question is how can we find inside compare method of Comparator implementation whether sort order is ascending (simple) or descending (reversed). One method I found is to place instanceof check for ReverseOrder class. But that is highly unreliable, as there are many implementations of Comparator class for reverse order.

In other words, what if we have to write a comparator, which should not allow reversed(or descending) order.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Aqeel Ashiq
  • 1,988
  • 5
  • 24
  • 57
  • I feel like the answer is: You don't. – Slaw Jun 21 '22 at 16:55
  • 1
    Comparators always sort in ascending order, for their own definition of ascending. – Andy Turner Jun 21 '22 at 17:03
  • I think this will answer your question, https://stackoverflow.com/a/1946845/4188827 – Santosh Jun 21 '22 at 17:23
  • 2
    When you write a comparator, *you* decide which order it implements. What comparator do you want to check with instanceof? Your own? And what ReverseOrder class? There is no such class in the standard API. – Holger Jun 21 '22 at 18:21

1 Answers1

3

You don't. There is absolutely no way to prevent a Comparator being converted to a descending-order comparator. If you are given a Comparator, then that defines ascending order, even if it's descending relative to another comparator.

If there is one unique, ascending order that you always want to use, then the type should implement Comparable, instead of having a Comparator, and you should use the natural ordering of the type.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413