Java

Comparable Interface – Java With Example

Comparable interface is mostly used to sort custom object arrays and lists.
By using Collections.sort, items that implement the Comparable interface may be automatically sorted in lists (and arrays) (and Arrays.sort). Let’s explore how to sort components of arrays and Wrapper classes that already implement Comparable before we look at how to sort an item of a custom object.

Example: Sorting arrays and Wrapper class

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Demo {
  public static void main(String[] args) {
    /*
     * Integer class implements Comparable
     * Interface so we can use the sort method
     */
    int[] arr = {11,55,22,0,89};
    Arrays.sort(arr);
    System.out.print("Sorted Int Array: ");
    System.out.println(Arrays.toString(arr));
        
    /*
     * String class implements Comparable
     * Interface so we can use the sort method
     */
    System.out.print("Sorted String Array: ");
    String[] names = {"Steve", "Ajeet", "Kyle"};
    Arrays.sort(names);
    System.out.println(Arrays.toString(names));
        
     /*
      * String class implements Comparable
      * Interface so we can use the sort method
      */
     System.out.print("Sorted List: ");
     List fruits = new ArrayList();
     fruits.add("Orange");
     fruits.add("Banana");
     fruits.add("Apple");
     fruits.add("Guava");
     fruits.add("Grapes");
     Collections.sort(fruits);
     for(String s: fruits) System.out.print(s+", ");
  }
}

Output:

Sorted Int Array: [0, 11, 22, 55, 89]
Sorted String Array: [Ajeet, Kyle, Steve]
Sorted List: Apple, Banana, Grapes, Guava, Orange,

You can see from the example above how simple it is to sort Arrays and lists of objects that implement the Comparable interface by just using the Collections.sort method (and Arrays.sort).
However, you must implement the Comparable interface in our custom class if you wish to sort the objects of that class.

There is just one method on this interface, which is:

public abstract int compareTo(T obj)

Since this function is abstract, if you implement the Comparable interface, your class must implement this method as well.

To further grasp this, let’s look at an illustration:

Example: Sorting Custom object by implementing Comparable interface

As you can see, I wanted to order the objects in my Author class, so I built the Comparable interface. You may construct logic depending on the requirements, however I have placed the sorting logic in the compareTo() function. If the last name is the same, then I wanted to order the author names by first name. The first line of the compareTo() function is sufficient to sort simply by last name.

Author class

public class Author implements Comparable<Author> {

  String firstName;
  String lastName;
  String bookName;
  Author(String first, String last, String book){
	this.firstName = first;
	this.lastName = last;
	this.bookName = book;
  }
	
  @Override
  /*
   * This is where we write the logic to sort. This method sort 
   * automatically by the first name in case that the last name is 
   * the same.
   */
  public int compareTo(Author au){
     /* 
      * Sorting by last name. compareTo should return < 0 if this(keyword) 
      * is supposed to be less than au, > 0 if this is supposed to be 
      * greater than object au and 0 if they are supposed to be equal.
      */
     int last = this.lastName.compareTo(au.lastName);
     //Sorting by first name if last name is same d
     return last == 0 ? this.firstName.compareTo(au.firstName) : last;
  }
}

Sorting class: SortAuthByNames

import java.util.ArrayList;   
import java.util.Collections;
public class SortAuthByNames{  
   public static void main(String args[]){  
      // List of objects of Author class
      ArrayList<Author> al=new ArrayList<Author>(); 
      al.add(new Author("Henry","Miller", "Tropic of Cancer"));  
      al.add(new Author("Nalo","Hopkinson", "Brown Girl in the Ring"));
      al.add(new Author("Frank","Miller", "300"));
      al.add(new Author("Deborah","Hopkinson", "Sky Boys"));
      al.add(new Author("George R. R.","Martin", "Song of Ice and Fire"));
      
      /*
       * Sorting the list using Collections.sort() method, we
       * can use this method because we have implemented the 
       * Comparable interface in our user defined class Author
       */
      Collections.sort(al);  
      for(Author str:al){  
    	  System.out.println(str.firstName+" "+
          str.lastName+" "+"Book: "+str.bookName);  
      } 
   }  
}  

Output:

Deborah Hopkinson Book: Sky Boys
Nalo Hopkinson Book: Brown Girl in the Ring
George R. R. Martin Book: A Song of Ice and Fire
Frank Miller Book: 300
Henry Miller Book: Tropic of Cancer

You could be asking yourself, “Why didn’t I write that logic?” Since first name and last name are strings, I have used the string class’s compareTo() function, which does the identical action.

However, you may express the reasoning like this if the items we are comparing are of a different type, say int:
Say we want to sort the objects by empAge and we have an object of the Employee class with (empId, empName, empAge).

public int compareTo(Employee e){  
   if(this.empAge==e.empAge)  
      return 0;  
   else if(this.empAge>e.empAge)  
      return 1;  
   else  
      return -1;  
}

or

public int compareTo(Employee e){  
return this.empAge > e.empAge ? 1 : this.empAge < e.empAge ? -1 : 0;
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button