排序不可比较的元素列表

时间:2013-07-02 17:54:54

标签: java comparable

今天我被问到这个面试问题:

  

如果我的Person课程包含nameagesalary字段,我会将Person的100个新实例放入ArrayList 1}},然后执行Collections.sort(list),然后根据列表的哪个参数进行排序?

我知道我需要Person类工具Comparable,然后覆盖compareTo,但如果我不这样做,会发生什么?

4 个答案:

答案 0 :(得分:12)

它不会编译:Collections.sort的单参数版本需要Comparable的列表。具体而言,List<T> T实施Comparable<? super T>

答案 1 :(得分:5)

是的,你可以在不使元素实现Comparable Interface的情况下对集合进行排序,你可以这样做

List<YourType> theList = new ArrayList<>();
Collections.sort(theList, new Comparator<YourType>(){
    public int compare(YourType obj1, YourType obj2) {
                   // this method should return < 0, 0 or > 0 
                   // whether obj1 is less than, equal to 
                   // or greather than obj2
                    return 0; 
    }
});

/ edit,

如果你使用Collections.sort(List),那么只有当列表是通用的并且它的元素实现Comparable时它才会编译。如果是这样,那么每个元素上的compareTo(Obj)的实现将决定在调用sort(List)方法后列表中的排序

答案 2 :(得分:3)

作为Collections API声明:

public static <T extends Comparable<? super T>> void sort(List<T> list)

根据元素的自然顺序,将指定列表按升序排序。列表中的所有元素都必须实现Comparable接口。此外,列表中的所有元素必须是可相互比较的(即,e1.compareTo(e2)不得对列表中的任何元素e1和e2抛出ClassCastException。)

答案 3 :(得分:0)

如果Person类没有实现Comparable<Person>,那么(编译器会通知你):

  

绑定不匹配:类型sort(List<T>)的通用方法Collections不适用于参数(List<Person>)。推断类型Person不是有界参数<T extends Comparable<? super T>>的有效替代。

(如果您碰巧有Comparator<Person>Collections.sort(myList, myComparator)会按照比较器指定的顺序对其进行排序。)