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
Java
// Java Program to Sorting Elements illustrating // Array.srt) and Collection.sort() method // Naive approach // Importing all classes of // java.util package import java.util.*; // Class class GFG { // Main driver method public static void main(String[] args) { // Case 1: Array of Integer using sort() // Sorting array of integers // using Arrays.sort() // Custom input entries int [] a = { 8 , 9 , 1 , 5 , 3 , 0 }; // Print the array before sorting System.out.println( "Before Sorting: " + Arrays.toString(a)); // By default sorting is in ascending order Arrays.sort(a); // Print the array after sorting System.out.println( "After Sorting: " + Arrays.toString(a)); // Case 2: Array of string using sort() // Sorting array of Strings // using Arrays.sort() String[] str = { "Ankit" , "Parul" , "Swati" , "Tarun" , "Akshat" }; // Print the input array of string before sorting System.out.println( "Before Sorting: " + Arrays.toString(str)); // Sort() method Arrays.sort(str); // Print the input array of string before sorting System.out.println( "After Sorting: " + Arrays.toString(str)); // Case 3: Collections.sort // Sorting List of String Collections.sort() // Creating an list object of string type // Custominput elements in object List<String> lt = Arrays.asList( "Red" , "Blue" , "Green" , "Black" ); // Print the elements before sorting System.out.println( "Before Sorting: " + lt); Collections.sort(lt); // Print the elements after sorting System.out.println( "After Sorting:: " + lt); } } |
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
Java
// Java Program to Sorting Elements of Arrays and Wrapper // Classes that Already Implements Comparable // Importing all classes from // java.util package import java.util.*; // Class 1 // Helper class class Student implements Comparable<Student> { // Member variables of this class private int rollno; private String name; private Double marks; // Constructor of this class public Student( int rollno, String name, Double marks) { // This keyword refers to // current object itself this .rollno = rollno; this .name = name; this .marks = marks; } // Sorting based on marks of Students public int compareTo(Student s) { return this .marks.compareTo(s.marks); } public String toString() { return "Student{" + "RollNo=" + rollno + ", Name='" + name + '\ '' + ", Marks=" + marks + '}' ; } } // Class 2 // Main class class GFG { // main driver method public static void main(String args[]) { // Creating an ArrayList of user-defined // type(Student) ArrayList<Student> arr = new ArrayList<>(); // Adding elements to object created above // Custom input entries arr.add( new Student( 1 , "Ankush" , 98.0 )); arr.add( new Student( 2 , "Akshat" , 99.0 )); arr.add( new Student( 3 , "Parul" , 87.0 )); arr.add( new Student( 4 , "Tarun" , 78.0 )); arr.add( new Student( 5 , "Swati" , 90.0 )); // Iterating over the above ArrayList for ( int i = 0 ; i < arr.size(); i++) // Print the ArrayList elements as // in order added System.out.println(arr.get(i)); // Calling the Collection.sort() method // to sort elements of ArrayList Collections.sort(arr); // Printing the ArrayList after sorting System.out.println( "\nAfter Sorting :\n" ); for ( int i = 0 ; i < arr.size(); i++) System.out.println(arr.get(i)); } } |
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}