VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-override-compareto-method-in-java/

⇱ How to Override compareTo() Method in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Override compareTo() Method in Java?

Last Updated : 23 Jul, 2025

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 for Primitive class arrays and wrapper class arrays and   for 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.

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.


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 the Comparable interface to sort objects by age.
  • The GFG class implements Comparable<GFG>, allowing instances to be compared and sorted.
  • The main method creates an array and an ArrayList of GFG objects, sorts them using the overridden compareTo() method, and prints the sorted results.
Comment