Open In App

How to Override compareTo Method in Java?

Improve
Improve
Like Article
Like
Save
Share
Report

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.

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




// Java Program to show how to override the compareTo()
// method of comparable interface
import java.util.*;
 
// implementing Comparable interface
public class GFG implements Comparable<GFG> {
 
    String name;
    int age;
 
    // Class constructor
    GFG(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
    public int getage() { return age; }
    public String getname() { return name; }
    public static void main(String[] args)
    {
        // Creating GFG class object
        GFG ob[] = new GFG[4];
 
        // Inserting elements in the 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);
 
        // sort the array,using overridden method
        Arrays.sort(ob);
 
        for (GFG o : ob) {
 
            // printing the sorted array objects name and
            // age
            System.out.println(o.name + " " + o.age);
        }
 
        // if you want to create a dynamic array ,then you
        // can create an arraylist
        ArrayList<GFG> objects = new ArrayList<>();
 
        // creating a new GFG object
        GFG newObject1 = new GFG("Rohan Devaki", 20);
 
        // inserting the new object into the arraylist
        objects.add(newObject1);
 
        // creating a new GFG object
        GFG newObject2 = new GFG("Algorithammer", 22);
 
        // inserting the new object into the arraylist
        objects.add(newObject2);
 
        // using Collections to sort the arraylist
        Collections.sort(objects);
 
        for (GFG o : objects) {
            // printing the sorted objects in arraylist by
            // name and age
            System.out.format("%s  %d\n", o.name, o.age);
        }
    }
    // Overriding compareTo() method
    @Override public int compareTo(GFG o)
    {
        if (this.age > o.age) {
 
            // if current object is greater,then return 1
            return 1;
        }
        else if (this.age < o.age) {
 
            // if current object is greater,then return -1
            return -1;
        }
        else {
 
            // if current object is equal to o,then return 0
            return 0;
        }
    }
}


Output

Ravi 12
Aayush 14
Sachin 19
Mohit 20
Rohan Devaki  20
Algorithammer  22


Last Updated : 23 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads