Code:
public class CompareTest {
public static void main(String[] args) {
ArrayList list = new ArrayList();
(list).add(new CompareTest());
Arrays.sort(list.toArray()); //Does not throw Exception , why ?
Collections.sort(list); //throws ClassCastException
}
}
As per Java Doc: Arrays#sort
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface.
Why does Arrays#sort , doesnt throw ClassCastException
as stated by JavaDoc ?
Sorting an array of Objects The natural ordering is defined by implementation of the compareTo() method which determines how the current object (obj1) is compared to another (obj2) of the same type. The order is based on return value (an integer number, say x) of the compareTo() method: obj1 > obj2 if x > 0.
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort. The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist).
To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.
As mentioned in the official JavaDoc, Arrays. sort uses dual-pivot Quicksort on primitives. It offers O(n log(n)) performance and is typically faster than traditional (one-pivot) Quicksort implementations. However, it uses a stable, adaptive, iterative implementation of mergesort algorithm for Array of Objects.
Because the source code of Arrays.sort()
has this shortcut :
int nRemaining = hi - lo;
if (nRemaining < 2)
return; // Arrays of size 0 and 1 are always sorted
So it doesn't bother checking if the elements of the array implement Comparable, because it doesn't have to sort an array that has only one element.
Note that the javadoc doesn't guarantee that a ClassCastException is thrown.
Because it has only one element...And the Array.sort()
will end without sorting if there are elements less than 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With