代码
1 | public static void main(String[] args) { |
输出:1
2
3
4
55
4
3
2
1
分析
Comparator
- 比较器
- java.util包
- 接口
- 用于排序和分组
- 常用于数组和列表
- Arrays.sort(T[],Comparator<? super T> c)
- Collections.sort(List
list,Comparator<? super T> c)
原理
List.java1
2
3
4
5
6
7
8
9default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
- 调用List默认接口实现
- 实际调用Arrays.sort(a, (Comparator) c);
Arrays.java1
2
3
4
5
6
7
8
9
10public static <T> void sort(T[] a, Comparator<? super T> c) {
if (c == null) {
sort(a);
} else {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a, c);
else
TimSort.sort(a, 0, a.length, c, null, 0, 0);
}
}
- LegacyMergeSort归并排序,默认不使用
- TimSort利用合并和插入排序
指定Comparator逆序
1 | Collections.sort(result, Collections.reverseOrder()); |
源码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23public static <T> Comparator<T> reverseOrder() {
return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
}
private static class ReverseComparator
implements Comparator<Comparable<Object>>, Serializable {
private static final long serialVersionUID = 7207038068494060240L;
static final ReverseComparator REVERSE_ORDER
= new ReverseComparator();
//逆序
public int compare(Comparable<Object> c1, Comparable<Object> c2) {
return c2.compareTo(c1);
}
private Object readResolve() { return Collections.reverseOrder(); }
@Override
public Comparator<Comparable<Object>> reversed() {
return Comparator.naturalOrder();
}
}