背景
java 的Array.sort()
或者.stream.sorted()
都会使用Comparable<T>
作为参数
目前需要了解这些排序函数究竟是升序还是降序的
一句话答案
所有的排序都是升序的ascending
原因
Array.sort()
, .stream.sorted()
都使用Comparable<T>
这个类,都需要实现接口int compare(T o1, T o2);
我们看看接口compare
的注释:
Params:
o1 – the first object to be compared. o2 – the second object to be compared.
Returns:
a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
int compare(T o1, T o2);
入参有两个:第一个参数o1
,第二个是o2
返回值:
- 如果
o1 < o2
返回负数
- 如果
o1 > o2
返回正数
- 如果
o1 = o2
,返回0
再看看注释java.util.Comparator<T>
, 默认都是natural ordering
/**
* Returns a comparator that imposes the reverse of the <em>natural
* ordering</em>.
*
* <p>The returned comparator is serializable and throws {@link
* NullPointerException} when comparing {@code null}.
*
* @param <T> the {@link Comparable} type of element to be compared
* @return a comparator that imposes the reverse of the <i>natural
* ordering</i> on {@code Comparable} objects.
* @see Comparable
* @since 1.8
*/
public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {
return Collections.reverseOrder();
}