Sorting a list of non-comparable elements

2019-06-24 12:14发布

Today I was asked this interview question:

If I have a Person class with name, age and salary fields, and I put 100 new instances of this Person in an ArrayList, and then do Collections.sort(list), then on what parameter will the list be sorted?

I understand that I need to have the Person class implement Comparable and then override compareTo, but if I don't do that, what will happen?

4条回答
乱世女痞
2楼-- · 2019-06-24 12:45

as the Collections API states:

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

Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

查看更多
Anthone
3楼-- · 2019-06-24 12:45

If the Person class does not implement Comparable<Person>, then (as the compiler will inform you):

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<Person>). The inferred type Person is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>.

(If you happened to have a Comparator<Person> lying around, Collections.sort(myList, myComparator) would sort it by the ordering specified by the comparator.)

查看更多
戒情不戒烟
4楼-- · 2019-06-24 12:53

It wouldn't compile: the 1-argument version of Collections.sort expects a list of Comparables. Specifically, a List<T> where T implements Comparable<? super T>.

查看更多
SAY GOODBYE
5楼-- · 2019-06-24 12:59

Yes you can sort a collection without making the elements implement the Comparable Interface, you do this

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,

if you use Collections.sort(List) then it will compile only if the list is generic and it's elements implements Comparable. And if so, then the implementation of the compareTo(Obj) on each element is what will determine the ordering in the list after the sort(List) method is called

查看更多
登录 后发表回答