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 March 28, 2023 by Prepbytes

An interface in the Java programming language is used to specify a behavior that classes must implement. Java provides us with two such interfaces: Comparable and Comparator in java! Comparable is used in Java to sort objects using natural ordering, whereas Comparator is used to sort attributes of different objects. Comparable and Comparator in java are interfaces used to compare objects. This article will provide a proper explanation of the difference between Comparable and Comparator in java, along with examples.

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
In conclusion, both Comparable and Comparator in java are interfaces used for object comparison in Java. The Comparable interface is used to define the natural ordering of objects, while the Comparator interface is used to define a custom ordering of objects. Classes implement the Comparable interface and override the compareTo() method to enable default ordering. Comparator is a Java functional interface that can sort objects. It is used for object customization. The comparator provides the compare() method, which can be overridden to provide custom comparison logic. For natural or default ordering, comparable can be used. Custom ordering is possible with Comparator. Comparable offers only one sorting sequence. For example Sort by id or name and whereas the Comparator offers a variety of sorting sequences. For example Sort by both id and name.Comparable makes changes to the class that implements it.Whereas Comparator has no effect on any class.

Frequently Asked Questions(FAQ)

Here are the FAQs on Comparable and Comparator in java:

Q1. When should I use Comparable in Java?
A: You should use Comparable in Java when the natural ordering of objects of a class is meaningful.

Q2. When should I use Comparator in Java?
A: You should use Comparator in Java when a custom ordering of objects of a class is needed, or when a class cannot implement Comparable.

Q3. How do I sort a collection of objects using Comparable in Java?
A: To sort a collection of objects using Comparable in Java, you can use the Collections.sort() method. This method sorts a list of objects in ascending order based on their natural ordering defined by the compareTo() method of the Comparable interface.

Q4. How do I sort a collection of objects using Comparator in Java?
A: To sort a collection of objects using Comparator in Java, you can use the Collections.sort() method and pass an instance of the Comparator class as a second argument. This method sorts a list of objects based on the custom ordering defined by the compare() method of the Comparator interface.

Q5. Can a class implement both Comparable and Comparator in Java?
A: Yes, a class can implement both Comparable and Comparator in Java. This allows you to sort objects using their natural ordering defined by the compareTo() method of the Comparable interface.

Leave a Reply

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