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

前端 未结 4 1779

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 to

4条回答
  •  清酒与你
    2021-02-01 02:27

    You (or rather, your comparator) decides.

    • If your Comparator's compare(T o1, T o2) return a negative when o1 is less than o2, you get ascending order (demo on ideone).
    • If your Comparator's compare(T o1, T o2) return a negative when o1 is greater than o2, you get descending order (demo on ideone).

    Another way of saying the same thing would be that sort assumes that the comparator orders the two items passed into it from smaller (o1) to greater (o2), and produces an ascending sort consistent with that ordering.

提交回复
热议问题