Sobes.tech
Junior — Middle

What are the differences between Comparator and Comparable interfaces in Java?

sobes.tech AI

Answer from AI

In Java, the interfaces Comparable and Comparator are used for comparing objects but serve different purposes:

  • Comparable — defines the natural order of objects. A class implements this interface so that objects can be compared with each other using the compareTo() method. It is typically used for default sorting.

  • Comparator — a separate object that defines an alternative way of comparing two objects. It is used when you need to sort objects by different criteria or when a class does not implement Comparable.

Example:

class Person implements Comparable<Person> {
    String name;
    int age;

    public int compareTo(Person other) {
        return this.name.compareTo(other.name); // natural order by name
    }
}

// Comparator for sorting by age
Comparator<Person> ageComparator = new Comparator<Person>() {
    public int compare(Person p1, Person p2) {
        return Integer.compare(p1.age, p2.age);
    }
};

Thus, Comparable sets a single comparison method within the class, while Comparator allows creating multiple external comparison methods.

What are the differences between Comparator and… - sobes.tech