排序不可比较的元素列表

Vic*_*tor 6 java comparable

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

如果我有一个Person带班name,agesalary领域,我把这个100个新的实例Person中的ArrayList,然后做Collections.sort(list),然后什么参数将列表进行排序?

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

ars*_*jii 13

它不会编译:1参数版本Collections.sort需要一个Comparables 列表.具体来说,实现的List<T>地方.TComparable<? super T>


Dav*_*ann 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; 
    }
});
Run Code Online (Sandbox Code Playgroud)

/编辑,

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