Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

sorting - What's the sort order of Java's Collections.sort(list, comparator)? small to big or big to small?

Apparently, it's not documented or I missed it.

Here's the link to the documentation and below's the text as an image:

EDIT(17/5): I think too many confused this question to be a comparator question. It is not. The comparator compares between 2 elements. According to that comparison, the list sorted. How? Ascending or Descending?

I'll refine/simplify the question even further: If the comparator decides that element A is smaller than element B. In the sorted list, will element A be located at a lower index than element B?

enter image description here

question from:https://stackoverflow.com/questions/17641920/whats-the-sort-order-of-javas-collections-sortlist-comparator-small-to-big

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The sort order is always ascending, where the Comparator defines which items are larger than others.

From the documentation for Collections.sort(List<T> list, Comparator<? super T> c):

Sorts the specified list according to the order induced by the specified comparator.

From the documentation for Comparator.compare(T,T):

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...