Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 244
Sudhakar Avatar asked Mar 16 '13 14:03

Sudhakar


People also ask

How to use Comparator with Arrays sort in Java?

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.

Is Arrays sort in Java stable?

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

Can we sort array using Comparator?

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.

Which algorithm does Arrays sort use in Java?

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.


2 Answers

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.

like image 169
JB Nizet Avatar answered Sep 27 '22 00:09

JB Nizet


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

like image 27
Pragnani Avatar answered Sep 23 '22 00:09

Pragnani