Collections.sort(List<T> list, Comparator<? super T> c) 源代码分析
2017-09-30 18:19
519 查看
Collections.sort(List list, Comparator? super T c) 源代码分析
Sorts the specified list according to the order induced by the specified comparator.
该方法主要细分为三个步骤:
将list装换成一个对象数组。
将这个对象数组传递给Arrays类的sort方法(也就是说collections的sort其实本质是调用了Arrays.sort)。
完成排序之后,再一个一个地,把Arrays的元素复制到List中。
具体例子见LintCode156题合并区间,修改实例如下:
Sorts the specified list according to the order induced by the specified comparator.
public static <T> void sort(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]); } }
该方法主要细分为三个步骤:
将list装换成一个对象数组。
将这个对象数组传递给Arrays类的sort方法(也就是说collections的sort其实本质是调用了Arrays.sort)。
完成排序之后,再一个一个地,把Arrays的元素复制到List中。
具体例子见LintCode156题合并区间,修改实例如下:
// 先对区间进行排序,使用一个匿名内部类 Collections.sort(intervals, new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { return o1.start - o2.start; } });
相关文章推荐
- Collections.sort(List<T> list, Comparator<? super T> c) 应用
- 使用Collections.sort(List<T>,Comparator<? super T>)给List<String>排序(一)
- 使用Collections.sort(List<T>,Comparator<? super T>)给List<String>排序
- sort(List<T> list, Comparator<? super T> c) 根据比较器产生的顺序排序
- 剑指Offer——巧妙使用sort(List<T>,Comparator<? super T>)比较器
- 剑指Offer——巧妙使用sort(List<T>,Comparator<? super T>)比较器
- Collections.sort(List<T> Comparator) 自定义排序
- 【Java】如何给List集合排序Collections.sort(list,new Comparator<Entity>)
- 使用Collections.sort(List<T>,Comparator<T>)给List<String>排序(一)
- 使用Collections.sort(List<T>,Comparator<T>)给List<String>排序(一)
- public static <T extends Comparable<? super T>> void sort (List<T> list)的理解
- <stl>list::sort源码分析
- Collections.copy(List<? super T> dest, List<? extends T> src) 抛出异常 Source does not fit in dest 原因剖析
- Java List<>排序——重载Collections.sort方法
- android Collections.sort(List<T> list) 与JAVA Collections.sort(List<T> list)
- java Arrays.sort(T[] a, Comparator<? super T> c)调用一个已经封装好的排序规则进行排序
- android Collections.sort(List<T> list) 与JAVA Collections.sort(List<T> list)
- comparator<> || Collections.sort -------------------------java
- 集合中按照商品价格排序,按照学生编号排序,Collections集合里的sort方法,Comparator<T>接口,Comparable<T>接口,
- 实体类集合(List<Object>)根据实体类的一个或者多个属性对集合进行排序-Collections.sort