-1

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.

4
  • I feel like the answer is: You don't. Commented Jun 21, 2022 at 16:55
  • 1
    Comparators always sort in ascending order, for their own definition of ascending. Commented Jun 21, 2022 at 17:03
  • I think this will answer your question, stackoverflow.com/a/1946845/4188827 Commented Jun 21, 2022 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. Commented Jun 21, 2022 at 18:21

1 Answer 1

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.

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.