![]() |
VOOZH | about |
As we know, there are basically two types of sorting technique in Java:
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 thecompareTo() 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.
Ravi 12 Aayush 14 Sachin 19 Mohit 20 Rohan Devaki 20 Algorithammer 22
compareTo() method from the Comparable interface to sort objects by age. GFG class implements Comparable<GFG>, allowing instances to be compared and sorted. main method creates an array and an ArrayList of GFG objects, sorts them using the overridden compareTo() method, and prints the sorted results.