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