Sorting a list of non-comparable elements

拟墨画扇 提交于 2019-12-08 21:08:40

问题


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?


回答1:


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




回答2:


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




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/17432489/sorting-a-list-of-non-comparable-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!