Arrays.sort(object[]) is not throwing classcastexception
Asked Answered
C

3

6

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 ?

Capo answered 16/3, 2013 at 14:22 Comment(0)
I
7

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.

Inland answered 16/3, 2013 at 14:28 Comment(2)
Interesting - the same thing was "fixed" in TreeMap in Java 7, but apparently not in Arrays...Dibasic
So javadoc can be deceiving.Floriated
A
2

Because it has only one element...And the Array.sort() will end without sorting if there are elements less than 2

Anus answered 16/3, 2013 at 14:29 Comment(0)
V
0

The reason is that list has only one elemnt,the compareTo method never invoked in Arrays.sort,so the element is never cast to Comparable.

but it's invoked anyway in Collections.sort:

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]);
}
}

all elemnt is casting to T which extends from Comparable

Vortumnus answered 16/3, 2013 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.