Member-only story

Comparable vs. Comparator in Java

Saurav Kumar
4 min readSep 17, 2023

In Java, “Comparable” and “Comparator” are two interfaces used for sorting and comparing objects, but they serve different purposes and are used in different scenarios.

  1. Comparable Interface:
  • The Comparable interface is used to define the natural ordering of objects of a class. This means that if a class implements the Comparable interface, it provides a way to compare its instances based on specific criteria or attributes.
  • The Comparable interface defines a single method compareTo(Object o) that returns an integer value. This method compares the current object with the specified object (usually of the same class).
  • The compareTo method returns a negative integer if the current object is less than the specified object, zero if they are equal, and a positive integer if the current object is greater than the specified object.
  • Classes that implement Comparable can be easily sorted using methods like Arrays.sort() or Collections.sort().
  • Suppose you have a Book class that you want to sort based on the book's title (a natural ordering for books).
public class Book implements Comparable<Book> {
private String title;
private String author;
private int year;

// Constructors, getters, and setters

@Override
public int compareTo(Book other) {
// Compare books based on their titles
return this.title.compareTo(other.title);
}
}

--

--

Saurav Kumar
Saurav Kumar

Written by Saurav Kumar

Experienced Software Engineer adept in Java, Spring Boot, Microservices, Kafka & Azure.

No responses yet