I can not understand the method implementation and the logic of Collections.sort method. Here is the method implementation i found,
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
First of all this method return type is void. What is <T extends Comparable<? super T>> does in the method signature?
What is the purpose of using Array.sort here?
Also once we implement comparable or comparator where is the compare or compareTo method logic that we wrote take in to consider?
Please pay attention to where the generic type appears:
It basically declares and puts restriction on generic type
T. In this particular case it means:Tmust extendComparable<F>whereFmust be of typeTor a super type of it. This means thay if you have the following classes:You can still pass
List<Dog>toCollections.sort()(notice thatDogimplementsComparable<Animal>, notComparable<Dog>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
LinkedListhave poor random access (by index) performance, which makes most sorting algorithms quite slow (in the range ofO(n^2)). It’s better to defensively copy the whole collection and do the sorting on array becauseO(n + nlogn + n)is stillO(nlogn)– if you get big O notation).