As we know, there are basically two types of sorting technique in Java:
- First is internal sorting i.e that uses predefined sorting method ascending order Arrays.sort() for Primitive class arrays and wrapper class arrays and Collections.sort() for collections both methods sort the elements in ascending order.
- The second technique is for sorting the elements is using the comparator or comparable interface in a class.
- Comparator Interface: Implement the comparator interface in the class and override compare() method or pass the new comparator as the second argument in the sorting methods and change the sorting order according to the requirements. Comparator only works for wrapper type arrays and for collections like vector, ArrayList, etc.
- Comparable Interface: This interface implements a single sorting technique, and it affects the whole class. The comparable interface provides a compareTo() method to sort the elements.
- Comparator Interface: Implement the comparator interface in the class and override compare() method or pass the new comparator as the second argument in the sorting methods and change the sorting order according to the requirements. Comparator only works for wrapper type arrays and for collections like vector, ArrayList, etc.
To summarize, in Java, if sorting of objects needs to be based on natural order then use the compareTo() method of Comparable Interface. For Integers default natural sorting order is ascending and for Strings it is alphabetical. Whereas, if you're sorting needs to be done on attributes of different objects, or customized sorting then use compare() of Comparator Interface.
Overriding of the compareTo() Method
In order to change the sorting of the objects according to the need of operation first, we have to implement a Comparable interface in the class and override the compareTo() method. Since we have to sort the array of objects, traditional array.sort() method will not work, as it used to work on primitive types, so when we call the Arrays.sort() method and pass the object array, it will search, whether we have overridden the compareTo() method or not. Since we have overridden the compareTo() method, so objects will be compared by using this compareTo() methods, based on the age.
// Java Program to show how to override the compareTo() method of Comparable interface
import java.util.*;
// Class implementing Comparable interface
public class GFG implements Comparable<GFG> {
String name; // Name of the person
int age; // Age of the person
// Class constructor
GFG(String name, int age) {
this.name = name;
this.age = age;
}
// Getter for age
public int getAge() {
return age;
}
// Getter for name
public String getName() {
return name;
}
public static void main(String[] args) {
// Creating an array of GFG objects
GFG ob[] = new GFG[4];
// Initializing the array with GFG objects
ob[0] = new GFG("Aayush", 14);
ob[1] = new GFG("Ravi", 12);
ob[2] = new GFG("Sachin", 19);
ob[3] = new GFG("Mohit", 20);
// Sorting the array using the overridden compareTo() method
Arrays.sort(ob);
// Printing the sorted array objects' names and ages
for (GFG o : ob) {
System.out.println(o.name + " " + o.age);
}
// Creating a dynamic array (ArrayList) of GFG objects
ArrayList<GFG> objects = new ArrayList<>();
// Creating and adding new GFG objects to the ArrayList
GFG newObject1 = new GFG("Rohan Devaki", 20);
objects.add(newObject1);
GFG newObject2 = new GFG("Algorithammer", 22);
objects.add(newObject2);
// Sorting the ArrayList using the overridden compareTo() method
Collections.sort(objects);
// Printing the sorted ArrayList objects' names and ages
for (GFG o : objects) {
System.out.format("%s %d\n", o.name, o.age);
}
}
// Overriding compareTo() method to compare objects based on age
@Override
public int compareTo(GFG o) {
if (this.age > o.age) {
// Current object is older, return 1
return 1;
} else if (this.age < o.age) {
// Current object is younger, return -1
return -1;
} else {
// Ages are the same, return 0
return 0;
}
}
}
Output
Ravi 12 Aayush 14 Sachin 19 Mohit 20 Rohan Devaki 20 Algorithammer 22
Explanation of the above Program:
- This Java program demonstrates how to override the
compareTo()method from theComparableinterface to sort objects by age. - The
GFGclass implementsComparable<GFG>, allowing instances to be compared and sorted. - The
mainmethod creates an array and anArrayListofGFGobjects, sorts them using the overriddencompareTo()method, and prints the sorted results.