排序时Collections.sort和Comparator区别

本文详细比较了Java中Collections.sort和List.sort方法,以及它们与Comparator接口的关系,强调了Comparator的使用方式和它们底层调用的Arrays.sort方法。
摘要由CSDN通过智能技术生成

排序时Collections.sort和Comparator区别

先总结

Collections.sort和list.sort(new Comparator())无区别

comparator是一个接口,使用其排序时,只需要实现其int compare(T o1, T o2)方法然后调用**list.sort(new Comparator())**即可;collections.sort其实也是用的comparator的compare方法,只是它可以传一个comparator的实现或者传Null;

两者底层的排序都是用的Arrays类的static <T> void sort(T[] a, Comparator<? super T> c)方法

Comparator

Comparator接口的compare方法定义

o1<o2 return 负数;

o1==o2 return 0;

o1>o2 return 正数;

     * @param o1 the first object to be compared.
     * @param o2 the second object to be compared.
     * @return a negative integer, zero, or a positive integer as the
     *         first argument is less than, equal to, or greater than the
     *         second.
     * @throws NullPointerException if an argument is null and this
     *         comparator does not permit null arguments
     * @throws ClassCastException if the arguments' types prevent them from
     *         being compared by this comparator.
     */
    int compare(T o1, T o2);

使用时,List.sort()

再看List类的sort()方法实现

Collections

这个类有两个sort方法,带Comparator实现和不带Comparator实现的

  • void sort(List<T> list, Comparator<? super T> c)
public static <T> void sort(List<T> list, Comparator<? super T> c) {
        list.sort(c);
    }
  • void sort(List<T> list)
 public static <T extends Comparable<? super T>> void sort(List<T> list) {
        list.sort(null);
    }

这两个最终都用的是List的sort方法

也就是和Comparator用的是同一个方法’List.sort(Comparator<? super E> c)’

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值