Collections.sort implementation

后端 未结 5 1826
灰色年华
灰色年华 2021-02-08 18:38

I can not understand the method implementation and the logic of Collections.sort method. Here is the method implementation i found,

public static 

        
5条回答
  •  野性不改
    2021-02-08 19:05

    Please pay attention to where the generic type appears:

    public static > void sort(List list)
    

    It basically declares and puts restriction on generic type T. In this particular case it means: T must extend Comparable where F must be of type T or a super type of it. This means thay if you have the following classes:

    class Animal {}
    
    class Dog extends Animal implements Comparable {
        //...
    }
    

    You can still pass List to Collections.sort() (notice that Dog implements Comparable, not Comparable as usual).


    Arrays.sort() is used because this is where the sorting algorithm is implemented. Defensive copy from collection to array is needed to obey the contract and to avoid suboptimal runtime if collection is not random access.

    Some lists, like LinkedList have poor random access (by index) performance, which makes most sorting algorithms quite slow (in the range of O(n^2)). It's better to defensively copy the whole collection and do the sorting on array because O(n + nlogn + n) is still O(nlogn) - if you get big O notation).

提交回复
热议问题