排序时Collections.sort和Comparator区别

排序时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 void sort(T[] a, Comparator c)方法

Comparator

Comparator接口的compare方法定义

o1

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

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

也就是和Comparator用的是同一个方法’List.sort(Comparator c)’

你可能感兴趣的:(java,后端)