Java专题:Collections.sort()

1. 功能

实现对Collection内部对象排序,可对任意一组相似对象进行排序

2. 形式

Collections.sort(List<T> list)
Collections.sort(List<T> list, Comparator<? extends T> c)
  • Collections.sort(List list)

此方法适用于泛型T的实际类型实现了Comparable接口,重写了compare()方法。其底层实现如下:

public static <T extends Comparable<? super T>> void sort(List<T> list) {
    list.sort(null);
}
default void sort(Comparator<? super E> c) {
    Object[] a = this.toArray();
    Arrays.sort(a, (Comparator) c);   // 转化为了数组排序, 此时c=null;
    ListIterator<E> i = this.listIterator();
    for (Object e : a) { 
        i.next(); 
        i.set((E) e);
    }
}
// 继续找
public static <T> void sort(T[] a, Comparator<? super T> c) {
    if (c == null) {
        sort(a);  // Arrays类重载了sort()
    }
}
public static void sort(Object[] a) {
if (LegacyMergeSort.userRequested)
     legacyMergeSort(a);     // 使用归并排序
else
     ComparableTimSort.sort(a, 0, a.length, null, 0, 0); // 使用二分查找排序
}

在两个排序中都有,如下写法

Comparable pivot = (Comparable) a[start];

都使用了类型强制转换,也就是说 a 必须实现了Comparable接口,所以在未实现该接口而使用Collections.sort(),会报ClassCastException.

  • Collections.sort(List list, Comparator<? extends T> c)

此方法适合泛型类中未实现Comparable()接口,但是必须以实现Comparator接口的类作为参数,使用方法如下:

    Collections.sort(list,new Comparator<Student>(){  // 假设类型为Student,属性有id;按照id升序。
    	@Override
        public int compare(Student st1, Student st2) {
            return st1.id > st2.id? 1 : st1.id == st2.id ? 0 : -1;  // 根据返回的1、0、-1排序
        }
    });

总结

  • 使用 Collections.sort(List< T > list) 时,泛型类必须实现 Comparable 接口,重写 compareTo() 方法
  • 使用 Collections.sort(List< T > list, Comparator<? extends T> c) 时,必须以 Comparator实现类为参数,实现类实现的方法为compare()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值