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 packageimport java.util.*;Â
// Classclass 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 packageimport java.util.*;Â
// Class 1// Helper classclass 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 classclass 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}
Â
