Skip to main content

Sorting objects using Comparable Interface.

Points To Remember

  • Comparable is an interface and is available in java.lang package.
  • A class implementing it should override compareTo() method.
  • compareTo(Object obj) method returns 
    • negative integer if object obj is greater than the object with  whom it is compared.
    • 0 if both the objects have same values or are same.
    • positive integer if object obj have is less than the object with whom it is compared.
  • While overriding compareTo() method we must check
    • If the two objects belong to the same class, else throw ClassCastException.
    • If the two objects are not null, if either is null then throw NullPointerException.
  • We need not implement this class if we need to sort an array or list with objects like string, integers etc. 

Example:  Sorting a list of objects using Comparable Interface
Suppose we have a class Book with fields name and price and we need to sort the objects based on the name of the book, if the name of the book is same then we sort the book object based on the price of the book.

import java.util.*;

class Book implements Comparable<Book>{

String name;
int price;

public Book(String name, int price){

this.name=name;this.price=price;
}

@Override
public int compareTo(Book book)throws NullPointerException,ClassCastException{

if(this == null || book == null)
throw new NullPointerException();

if(this.getClass() != book.getClass())
throw new ClassCastException();

if(this.name.compareTo(book.name) != 0)
return this.name.compareTo(book.name);

return (this.price - book.price);
}

}

public class TestComparable{

public static void main(String args[]){

List<Book> list = new ArrayList<Book>();
Book book1 = new Book("Alchamist" , 150);
Book book2 = new Book("Monks" , 450);
Book book3 = new Book("Harry Potter" , 750);
Book book4 = new Book("Jungle Book" , 350);
Book book5 = new Book("Harry Potter" , 550);
list.add(book1);
list.add(book2);
list.add(book3);
list.add(book4);
list.add(book5);

Collections.sort(list);

for(Book book : list){
System.out.println("name="+book.name+" price="+book.price);
}

}


}

Output of the program :

name=Alchamist price=150

name=Harry Potter price=550

name=Harry Potter price=750

name=Jungle Book price=350

name=Monks price=450

Comments