![]() |
VOOZH | about |
Java provides the Comparable interface to sort objects using data members of the class. The Comparable interface contains only one method compareTo() that compares two objects to impose an order between them. It returns a negative integer, zero, or positive integer to indicate if the input object is less than, equal to, or greater than the current object. It is mainly used to sort the arrays or lists of custom objects.
Since all the Wrapper classes already implement Java Comparable interface, so it provides a default implementation of the compareTo(), and this is why Collections.sort() and Arrays.sort() functions can be used on these objects. Sorting elements of arrays and lists containing Wrapper classes as objects that already implement Comparable interface.
Illustration:
Input : {8 , 9 , 1 , 5 , 3 , 0}
Output : {0 , 1 , 3 , 5 , 8 , 9}
Input : {"Ankit", "Parul" , "Swati" , "Tarun", "Akshat"}
Output : {"Akshat" , "Ankit" , "Parul" , "Swati" , "Tarun"}
Implementation:
Example
Before Sorting: [8, 9, 1, 5, 3, 0] After Sorting: [0, 1, 3, 5, 8, 9] Before Sorting: [Ankit, Parul, Swati, Tarun, Akshat] After Sorting: [Akshat, Ankit, Parul, Swati, Tarun] Before Sorting: [Red, Blue, Green, Black] After Sorting:: [Black, Blue, Green, Red]
Now, if we want to sort a user-defined class into some specific order then we have to implement the Comparable interface which is present in java.lang package and provide the implementation of compareTo() method. The compareTo method also throws a NullPointerException or ClassCastException if the specified is null or if the type of the specified object prevents it from comparing to the object.
Implementation:
Example
Student{RollNo=1, Name='Ankush', Marks=98.0}
Student{RollNo=2, Name='Akshat', Marks=99.0}
Student{RollNo=3, Name='Parul', Marks=87.0}
Student{RollNo=4, Name='Tarun', Marks=78.0}
Student{RollNo=5, Name='Swati', Marks=90.0}
After Sorting :
Student{RollNo=4, Name='Tarun', Marks=78.0}
Student{RollNo=3, Name='Parul', Marks=87.0}
Student{RollNo=5, Name='Swati', Marks=90.0}
Student{RollNo=1, Name='Ankush', Marks=98.0}
Student{RollNo=2, Name='Akshat', Marks=99.0}