Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Difference between Comparable and Comparator in Java

Last Updated on December 28, 2023 by Ankit Kochar

Java, known for its robustness and flexibility, offers multiple ways to sort objects in collections. Two fundamental interfaces, Comparable and Comparator, play vital roles in implementing sorting functionalities. Understanding the differences between Comparable and Comparator is crucial for Java developers to effectively organize and manipulate collections.

In this article, we’ll delve into the nuances of Comparable and Comparator interfaces in Java. We’ll explore their functionalities, differences, best practices for their usage, and scenarios where one would be preferred over the other. By grasping the disparities between these interfaces, developers can optimize sorting mechanisms and tailor them to specific application requirements.

Comparable and Comparator in Java

The Comparable interface is used to define the natural order of objects of a class. The class that implements the Comparable interface can be sorted using the Collections.sort() method. The compareTo() method is implemented in the class to define the natural ordering of objects.

The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters).

Example
Here’s an example that demonstrates the use of the Comparable interface and below we have Code Implementation and Explanation

Code Implementation

import java.util.*;

class Student implements Comparable<Student> {
    private int id;
    private String name;
    private double gpa;

    public Student(int id, String name, double gpa) {
        this.id = id;
        this.name = name;
        this.gpa = gpa;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public double getGpa() {
        return gpa;
    }

    @Override
    public int compareTo(Student student) {
        if (this.gpa < student.gpa) {
            return -1;
        } else if (this.gpa > student.gpa) {
            return 1;
        } else {
            return 0;
        }
    }

    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student(1, "Alice", 3.7));
        students.add(new Student(2, "Bob", 3.5));
        students.add(new Student(3, "Charlie", 3.9));
        Collections.sort(students);
        for (Student student : students) {
            System.out.println(student.getName() + ": " + student.getGpa());
        }
    }
}

Output

Bob: 3.5
Alice: 3.7
Charlie: 3.9

Explanation
In this example, the Student class implements the Comparable interface and overrides the compareTo() method to compare two students based on their GPAs. The main() method creates a list of Student objects, adds some students to it, and sorts the list using the Collections.sort() method, which relies on the compareTo() method to compare the objects.

Comparator Interface

The java Comparator interface is used to sort objects in a user-defined class. This interface can be found in java.util package and includes two methods: compare(Object obj1,Object obj2) and equals (Object element).It supports multiple sorting sequences, which means you can sort the elements based on any data member, such as rollno, name, age, or anything else. It is used to define the custom ordering of objects. It provides two methods compare() and equals(). The compare() method is used to compare two objects and return an integer value that indicates their relative order. The equals() method is used to compare two Comparator objects for equality.

The compare() method takes two objects as parameters and returns an integer value that indicates the relative order of the two objects. If the first object is less than the second object, it returns a negative integer value. If the first object is greater than the second object, it returns a positive integer value. If the two objects are equal, it returns 0.

Example of Comparator Interface
Here’s an example that demonstrates the use of the Comparator interface and below we have code implementation and explanation

Code Implementation

import java.util.*;

class Book {
    private int id;
    private String title;
    private String author;
    private double price;

    public Book(int id, String title, String author, double price) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public double getPrice() {
        return price;
    }

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        books.add(new Book(1, "To Kill a Mockingbird", "Harper Lee", 15.0));
        books.add(new Book(2, "1984", "George Orwell", 12.0));
        books.add(new Book(3, "The Great Gatsby", "F. Scott Fitzgerald", 18.0));
        
        // sort the books by price in ascending order using a Comparator
        Collections.sort(books, new Comparator<Book>() {
            public int compare(Book b1, Book b2) {
                return Double.compare(b1.getPrice(), b2.getPrice());
            }
        });
        
        for (Book book : books) {
            System.out.println(book.getTitle() + " by " + book.getAuthor() + ": $" + book.getPrice());
        }
    }
}

Output:

1984 by George Orwell: $12.0
To Kill a Mockingbird by Harper Lee: $15.0
The Great Gatsby by F. Scott Fitzgerald: $18.0

Explanation:
In the above java program we demonstrate the use of comparator interface. In this example, the Book class represents a book with an ID, title, author, and price. The main() method creates a list of Book objects, adds some books to it, and sorts the list using a custom Comparator that compares the books by price in ascending order. The compare() method uses the Double. compare() method to compare the prices of the two books.

Differences between Comparable and Comparator in Java

Here we have the differences between Comparable and Comparator in Java

Comparable Comparator
It is part of a Java.lang package. It is a part of Java.util package.
It provides the compareTo() method to sort the objects. It provides compare() method to sort the objects. Also include equal() method.
It is implemented by the class itself. It is Implemented as a separate class or anonymous class.
Comparable modifies the class that implements it. Comparator doesn’t modify any class.
When the natural ordering of objects is meaningful. When a custom ordering of objects is needed.

So these are the main differences between Comparable and Comparator in java.

Conclusion
Comparable and Comparator interfaces in Java are essential tools for implementing sorting functionalities in collections. While Comparable defines the natural ordering within the class itself, Comparator allows for the creation of multiple custom sorting orders. Understanding the differences and best practices for using Comparable and Comparator empowers Java developers to efficiently organize and manipulate collections based on various sorting criteria, enhancing the flexibility and effectiveness of their applications.

FAQs on Comparable and Comparator in Java:

Here are the FAQs on Comparable and Comparator in java:

1. How does the Comparable interface facilitate sorting?
By implementing the compareTo method, objects can define their own logic for comparison. Sorting collections of objects that implement Comparable becomes possible using methods like Collections.sort().

2. When should I use Comparable?
Use Comparable when you want to define a default natural ordering for your objects. For instance, for classes like String, Integer, etc., the natural ordering is already defined, making them implement Comparable.

3. What is the Comparator interface in Java?
Comparator is an interface in Java used to define custom comparison logic for objects that do not implement Comparable or to create alternative sorting orders for objects that do implement Comparable.

4. How is Comparator different from Comparable?
Comparator allows defining multiple custom sorting orders for objects that might not have a natural ordering or to override the natural ordering defined by Comparable.

5. When should I use Comparator?
Use Comparator when you need to sort objects based on different criteria or when dealing with classes that do not implement Comparable and you want to define sorting logic externally.

6. Can a class implement both Comparable and use a Comparator?
Yes, a class can implement Comparable to define its natural ordering and also use a Comparator to define additional sorting orders as needed.

7. Which is more efficient, Comparable or Comparator?
In terms of efficiency, Comparable can be more efficient because the sorting logic is defined within the object itself. However, the choice between them should be based on the requirements and flexibility needed in the application.

8. Are there any best practices for using Comparable and Comparator?
It’s generally advisable to implement Comparable for defining natural ordering when applicable. Use Comparator for defining alternate or multiple sorting orders or when dealing with classes that don’t implement Comparable.

Leave a Reply

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