Does Array.sort() implements comparable ? When I looked at the Array Class it doesn't ,so How does the sort work here?

Viewed 336

How sorting is done here as I can see Arrays class doesn't implement Comparable.

        //Add values to Array
        int arrayname[]=new int[3];
        arrayname[0]=40;
        arrayname[1]=10;
        arrayname[2]=35;
            
        //Sort the elements
        Arrays.sort(arrayname);
            
        //Display values  
        System.out.println("Values in Array After Sorting:");
        for(int i=0;i<arrayname.length;i++){
            System.out.print(arrayname[i]+", ");
        } 
2 Answers

If you look into the Arrays.sort() code, it uses a class named ComparableTimSort internally. This class has a method ComparableTimSort.binarySort(Object[] a, int lo, int hi, int start), which actually expects that the elements in parameter a be Comparable.

Since Arrays.sort() is a static method, a utility method, Arrays doesn't directly implement Comparable. It is the elements in the array passed to it that need to be Comparable.

Related