collections.sort(list list, comparator c) 源代码分析

Collections.sort(List list, Comparator? super T c)
Sorts the specified list according to the order induced by the specified comparator.

1
2
3
4
5
6
7
8
9
public static <T> void (List<T> list, Comparator<? super T> c) {
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set(a[j]);
}
}

该方法主要细分为三个步骤:

  1. 将list装换成一个对象数组。
  2. 将这个对象数组传递给Arrays类的sort方法(也就是说collections的sort其实本质是调用了Arrays.sort)。
  3. 完成排序之后,再一个一个地,把Arrays的元素复制到List中。

具体例子见LintCode156题合并区间,修改实例如下:

1
2
3
4
5
6
7
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
return o1.start - o2.start;
}
});