Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]+", ");
        } 
like image 706
Sreekumar Sachidanandan Avatar asked Jan 20 '26 13:01

Sreekumar Sachidanandan


1 Answers

It does not have to. It uses the type's compareTo method. That means in the case of objects you need to implement the Comparable<T> interface.

See https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(java.lang.Object[])

For primitive types, they have a natural ordering already.

You can also pass a lambda or a method reference to have a custom sorting.

like image 199
Raildex Avatar answered Jan 22 '26 03:01

Raildex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!