I can not understand the method implementation and the logic of Collections.sort method. Here is the method implementation i found,
public static
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).