Sobes.tech
Junior

What is the difference between Comparator and Comparable?

sobes.tech AI

Answer from AI

Comparable is used to define the "natural" ordering of objects of a class. It implements the Comparable<T> interface, providing the compareTo(T o) method.

Comparator is used to define one or more alternative sorting orders. It implements the Comparator<T> interface, providing the compare(T o1, T o2) method.

The main differences are summarized in the table:

Attribute Comparable Comparator
Interface java.lang.Comparable<T> java.util.Comparator<T>
Sorting method compareTo(T o) compare(T o1, T o2)
Usage Inside the object class Separate class or lambda
Logic placement Within the class In a separate place
Number of orders Only one "natural" order Multiple alternative orders
Class modification Requires class modification Does not require class modification

Example of using Comparable:

// Class implementing Comparable for sorting by name
class Person implements Comparable<Person> {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int compareTo(Person other) {
        // Compare by name
        return this.name.compareTo(other.name);
    }

    @Override
    public String toString() {
        return "Person{" +
               "name='" + name + '\'' +
               ", age=" + age +
               '}';
    }
}

Example of using Comparator:

// Comparator for sorting by age
import java.util.Comparator;

class AgeComparator implements Comparator<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        // Compare by age
        return Integer.compare(p1.getAge(), p2.getAge());
    }
}