Core java - Advance Topics
  • Welcome
  • Schedule
  • 1) Exception Handling
    • 1) Introduction to Exception Handling
    • 2) Categories of Exceptions
    • 3) Creating a method that throws an exception
    • 4) Creating Custom Exception Classes
    • 5)What happens when an exception is thrown?
      • 5.1) Creating try-catch-finally blocks
      • 5.2) Using a method that throws a checked exception
      • 5.3) Using a method that throws a runtime exception
      • 5.4) Using a method that throws an error
      • 5.5) Will a finally block execute even if the catch block defines a return statement?
      • 5.6) What happens if both a catch and a finally block define return statement?
      • 5.7) What happens if a finally block modifies the value returned from a catch block?
      • 5.8) Can a try block be followed only by a finally block?
      • 5.9) Does the order of the exceptions caught in the catch blocks matter?
      • 5.10) Can I rethrow an exception or the error I catch?
      • 5.11) Can I declare my methods to throw a checked exception instead of handling it?
      • 5.12) I can create nested loops, so can I create nested try-catch blocks too?
      • 5.13) Should I handle errors?
    • 6) Best Practices
    • 7) Cheat Sheet
    • 8) Problems
  • 2) Wrapper Classes and Enums
    • 2.1) Creating objects of the wrapper classes
    • Enums
  • 3) Inner Classes
    • 3.1) Static nested class (also called static inner class)
    • 3.2) Inner class (also called member class)
    • 3.3) Anonymous inner class
    • 3.4) Method local inner classes
    • CheatSheet
  • 4) Generics
    • Multiple Type parameters in Generic classes
    • Inheritance using Generics
    • Generic interfaces
    • Generic Methods
    • Bounded type parameters
    • Applications
  • 5) Equals and Hashcode
    • Problems
  • CompareTo method overview
  • Basic DS
    • 1) Simple Array List
    • 2) Simple HashMap
  • 5) Collections Framework - Part 1
    • Introducing the collections framework
    • Working with the Collection interface
      • The core Collection interface
      • Methods of the Collection interface
    • Creating and using List, Set, and Deque implementations
      • List interface and its implementations
      • Iterators
      • Sorting List using custom sorting technique
      • Comparable Interface
      • Custom Sorting using comparator
      • ArrayList - Examples and practice problems
    • Stack
    • Linked List
    • LinkedList Operations
  • 6) Collections Framework - Part 2
    • Sets
      • Set Types
      • Array to Set (vice versa)
    • Maps
    • TreeMap
    • Autoboxing And Unboxing
  • Collections Framework - Part 3
    • Basics : DS , Number System
    • Internal Working
      • HashMap
      • HashSet
  • 7) Reflection API
  • 8) Annotations
  • 9) Reading Input From Various Sources
    • File Handling
    • Reading From Xml
    • Reading From JSON
  • 10) Multi-threading (Concurrency)
    • Protect shared data
    • Thread-safe access to shared data
  • 11) Design Patterns
    • Singleton
    • DI
  • 12) Internal Working of JVM
  • 13) Garbage Collection
  • 14) More on Strings (Buffer and Builder)
  • 15) Cloning and Immutable Class
    • 16) Serialization And Deserialization
    • Untitled
  • JAVA 8
    • Interface Changes
    • Lambda
    • Method Ref
    • Optional
    • Streams
    • Predicates
  • Practice Tests
    • Test - Collections
    • OOPS
    • S-OOPS
Powered by GitBook
On this page
  • Java Comparable interface intuition
  • Example 1:
  • Java Comparable interface Example 2
  • Coding Challenge:

Was this helpful?

  1. 5) Collections Framework - Part 1
  2. Creating and using List, Set, and Deque implementations

Comparable Interface

PreviousSorting List using custom sorting techniqueNextCustom Sorting using comparator

Last updated 6 years ago

Was this helpful?

We often need to compare two values in our Java programs. Comparing primitive values like int, char, float is very easy and can be done with comparison operators like <, >, == etc.

But comparing objects is a little different. For example, how would you compare two Employees? how would you compare two Students?

You need to explicitly define how the objects of user defined classes should be compared. For this purpose, Java provides two interfaces called Comparable and Comparator.

Java Comparable interface intuition

By default, a user defined class is not comparable. That is, its objects can’t be compared. To make an object comparable, the class must implement the Comparable interface.

The Comparable interface has a single method called compareTo() that you need to implement in order to define how an object compares with the supplied object -

public interface Comparable<T> {
     public int compareTo(T o);
}

When you define the compareTo() method in your classes, you need to make sure that the return value of this method is -

  • negative, if this object is less than the supplied object.

  • zero, if this object is equal to the supplied object.

  • positive, if this object is greater than the supplied object.

Many predefined Java classes like String, Date, LocalDate, LocalDateTime etc implement the Comparable interface to define the ordering of their instances.

Let’s now see an example to make things more clear.

Example 1:

public class Person implements Comparable<Person> {

	private String name;
	private int age;

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public int getAge() {
		return this.age;
	}

	public String getName() {
		return this.name;
	}

	@Override
	public String toString() {
		return "";
	}

	@Override
	public int compareTo(Person per) {
		if (this.age == per.age)
			return 0;
		else
			return this.age > per.age ? 1 : -1;
	}

	public static void main(String[] args) {
		Person e1 = new Person("Mohit", 25);
		Person e2 = new Person("Rahul", 33);

		int retval = e1.compareTo(e2);
		switch (retval) {
		case -1: {
			System.out.println("The " + e2.getName() + " is older!");
			break;
		}
		case 1: {
			System.out.println("The " + e1.getName() + " is older!");
			break;
		}
		default:
			System.out.println("The two persons are of the same age!");
		}
	}

}
The Rahul is older!

Java Comparable interface Example 2

The example below shows how to implement the Comparable interface in a user defined class and define the compareTo() method to make the objects of that class comparable.

import java.time.LocalDate;

public class Employee implements Comparable<Employee> {
    private int id;
    private String name;
    private double salary;
    private LocalDate joiningDate;

    public Employee(int id, String name, double salary, LocalDate joiningDate) {
        this.id = id;
        this.name = name;
        this.salary = salary;
        this.joiningDate = joiningDate;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public LocalDate getJoiningDate() {
        return joiningDate;
    }

    public void setJoiningDate(LocalDate joiningDate) {
        this.joiningDate = joiningDate;
    }

    // Compare Two Employees based on their ID
    /**
     * @param   anotherEmployee - The Employee to be compared.
     * @return  A negative integer, zero, or a positive integer as this employee
     *          is less than, equal to, or greater than the supplied employee object.
    */
    @Override
    public int compareTo(Employee anotherEmployee) {
        return this.getId() - anotherEmployee.getId();
    }

}

In the above example, we’re comparing two employees by their IDs.

We’re just returning this.getId() - anotherEmployee.getId() from the compareTo() function, which will be

  • negative if the ID of this employee is less then the ID of the supplied employee,

  • zero if the ID of this employee is equal to the ID of the supplied employee, and

  • positive if the ID of this employee is greater than the ID of the supplied employee.

It’s just a concise way of writing the following -

public int compareTo(Employee anotherEmployee) {
    if(this.getId() < anotherEmployee.getId()) {
        return -1;
    } else if (this.getId() > anotherEmployee.getId()) {
        return 1;
    } else {
        return 0;
    }
}

Let’s now see how the Employee objects can be sorted automatically by Collections.sort method -

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableExample {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();

        employees.add(new Employee(1010, "Rajeev", 100000.00, LocalDate.of(2010, 7, 10)));
        employees.add(new Employee(1004, "Chris", 95000.50, LocalDate.of(2017, 3, 19)));
        employees.add(new Employee(1015, "David", 134000.00, LocalDate.of(2017, 9, 28)));

        System.out.println("Employees (Before Sorting) : ");
        
        for(int i = 0 ; i < employees.size(); i++) {
        	System.out.println("id "+ employees.get(i).getId());
        	System.out.println("name " + employees.get(i).getName());
        	System.out.println("salary " + employees.get(i).getSalary());
        	System.out.println("joiningDate " + employees.get(i).getJoiningDate());
        }

        // This will use the `compareTo()` method of the `Employee` class to compare two employees and sort them.
        Collections.sort(employees);

        System.out.println("\nEmployees (After Sorting) : ");
        
        for(int i = 0 ; i < employees.size(); i++) {
        	System.out.println("id "+ employees.get(i).getId());
        	System.out.println("name " + employees.get(i).getName());
        	System.out.println("salary " + employees.get(i).getSalary());
        	System.out.println("joiningDate " + employees.get(i).getJoiningDate());
        }
    }
}
Employees (Before Sorting) : 
id 1010
name Rajeev
salary 100000.0
joiningDate 2010-07-10
id 1004
name Chris
salary 95000.5
joiningDate 2017-03-19
id 1015
name David
salary 134000.0
joiningDate 2017-09-28

Employees (After Sorting) : 
id 1004
name Chris
salary 95000.5
joiningDate 2017-03-19
id 1010
name Rajeev
salary 100000.0
joiningDate 2010-07-10
id 1015
name David
salary 134000.0
joiningDate 2017-09-28

Any class that implements the Comparable interface works out of the box with Sorted Sets and Sorted Maps.

Coding Challenge:

Once you define how the objects should be compared using any of these interfaces, you’ll be able to sort them using various library functions like or .

Collections.sort
Arrays.sort
LogoJava Comparator | HackerRankHackerRank