Java Comparable Interface

Java allows comparing primitives values easily using the operators <, <=, >, >=, ==, !=.

But to compare objects using these operators are not supported and it is necessary to use a different approach.

How to compare two Tasks objects in a simple task manager system. Java allows comparing objects using Comparable interface. After defined how to compare the objects it is easy to sort the objects using a function available on Collections or Arrays classes.

Collections.sort(tasks);
Arrays.sort(tasks);

A class is not comparable by default. To make a class comparable, the class needs to implement the interface Comparable and override the method compareTo().

The method compareTo() defines how the objects are compared between each other. Below is the definition of the Comparable interface.

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

The method compareTo() returns an integer that defines if the object is less than, equal to or greater than the other one.

  • Negative – Indicates if the current object is less than the other object.
  • Zero – Indicates if the current object is equal to the other object.
  • Positive – Indicates if the current object is greater than the other object.

Java has many classes that implement Comparable interface in order to define the order of the object like String, Integer, Date, Calendar and many others.

Example

The example shows how to implement the Comparable interface in a given class and how to define the method compareTo() to compare two different objects.

The example will compare the attribute priority using the methodcompareTo() defined in the Integer class.


import java.util.Date;
import java.util.Objects;
import java.util.UUID;

public class Task implements Comparable {

    private String id;
    private String name;
    private String description;
    private Integer priority;
    private Date created;
    private Status status;

    public Task() {
    }

    public Task(String name, Integer priority) {
        this.id = UUID.randomUUID().toString();
        this.name = name;
        this.priority = priority;
        this.created = new Date();
    }
    
    // The Getters and Setters were omitted

    public int compareTo(Task anotherTask) {
        return this.priority.compareTo(anotherTask.priority);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Task task = (Task) o;
        return id.equals(task.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public String toString() {
        return "{name=" + name + ", priority=" + priority +"}";

    }
}

The compareTo() method could be implemented as shown below.

@Override
public int compareTo(Task anotherTask) {
   if(this.priority < anotherTask.getPriority()) {
       return -1;
   }
   if(this.priority > anotherTask.getPriority()) {
       return 1;
   }
   return 0;
}

The code below shows how to sort a list of given Tasks based on the order defined in the Task class.

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

public class ComparableTest {

    public static void main(String[] args) {

        List listOfTasks = new ArrayList<>();
        listOfTasks.add(new Task("Task 1", 1));
        listOfTasks.add(new Task("Task 2", 3));
        listOfTasks.add(new Task("Task 3", 2));
        listOfTasks.add(new Task("Task 4", 5));


        System.out.println("Before Sort");
        System.out.println(listOfTasks);

        Collections.sort(listOfTasks);

        System.out.println("After Sort");
        System.out.println(listOfTasks);
    }
}
# output:

Before Sort
[{name=Task 1, priority=1}, {name=Task 2, priority=3}, {name=Task 3, priority=2}, {name=Task 4, priority=5}]

After Sort
[{name=Task 1, priority=1}, {name=Task 3, priority=2}, {name=Task 2, priority=3}, {name=Task 4, priority=5}]