简体   繁体   中英

Sorting a list of non-comparable elements

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?

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

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

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).

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>> <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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM