Sobes.tech
Junior — Middle

What is the main difference between the Comparable and Comparator interfaces in Java when sorting objects?

sobes.tech AI

Answer from AI

The main difference between the Comparable and Comparator interfaces in Java:

  • Comparable — an interface implemented by the class itself, defining the natural order of comparison through the compareTo() method. It is used when the object knows how to compare itself with other objects of the same type.

  • Comparator — a separate interface implemented in a different class or lambda expression to define the order of objects without modifying the class itself. It allows creating different comparison methods for the same class.

Example:

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

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

// Comparator for comparing by age
Comparator<Person> ageComparator = (p1, p2) -> Integer.compare(p1.age, p2.age);

Thus, Comparable sets the natural order within the class, while Comparator provides an external, additional sorting method.

What is the main difference between the Comparable… - sobes.tech