BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Comparable Interface in Java with example

Last Updated: May 26, 2024 by Chaitanya Singh | Filed Under: java

Comparable interface is mainly used to sort the arrays (or lists) of custom objects. Lists (and arrays) of objects that implement Comparable interface can be sorted automatically by Collections.sort (and Arrays.sort).

Before we see how to sort an objects of custom objects, lets see how we can sort elements of arrays and Wrapper classes that already implements Comparable.

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<String> fruits = new ArrayList<>();
    fruits.add("Orange");
    fruits.add("Banana");
    fruits.add("Apple");
    fruits.add("Guava");
    fruits.add("Grapes");
    Collections.sort(fruits);
    System.out.println(String.join(", ", fruits));
  }
}

Output:

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

In the above example, you have seen that how easy it is to sort the Arrays and list of objects that implements Comparable interface, you just need to call the Collections.sort (and Arrays.sort).
However if you want to sort the objects of custom class then you need to implement the Comparable interface in our custom class.

This interface has only one method which is:

public abstract int compareTo(T obj)

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

Let’s take an example to understand this better:

Example: Sorting Custom object by implementing Comparable interface

As you can see I have implemented the Comparable interface in my Author class because I want to sort the objects of this class. I have written the logic of sorting in the compareTo() method, you can write logic based on the requirement. I wanted to sort the author names by last name first and if the last name is same then by first name. If you want to sort by the last name only then first line inside compareTo() method is enough.

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

Note: We should write the compareTo() method in such a way that if this( I am referring to the this keyword here) is less than the passed object then it should return negative, if greater than positive and zero if equal.

You may be wondering why I didn’t write that logic? Because first name and last name are strings, I have called the compareTo() method of string class, which does exactly the same.

However if the things we are comparing are of other type such as int then you can write the logic like this:
Let’s say object of Employee class is (empId, empName, empAge) and we want to sort the objects by 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;
}

Top Related Articles:

  1. Break statement in Java with example
  2. Multilevel inheritance in java with example
  3. Java Scanner class with examples
  4. How to Convert an array to ArrayList in java
  5. Java 8 features with examples

Tags: Collections

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. sri says

    May 17, 2024 at 3:39 PM

    This following code is showing error—-
    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+”, “);

    error: incompatible types: Object cannot be converted to String
    for(String s: fruits) System.out.print(s+”, “);
    ^
    please look into this,sir. thank you.

    Reply
    • Chaitanya Singh says

      May 26, 2024 at 9:01 AM

      You can use the String.join() method instead of this. I have updated the program in the article, you can refer the updated code.

      Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap