Comparable vs Comparator

In Java, both Comparable and Comparator interfaces are used for sorting objects, but they have different purposes and are implemented in different ways.

Comparable Interface:

  • The Comparable interface is used for natural ordering of objects. When a class implements Comparable, it means that instances of that class can be compared with each other based on their natural order.
  • The compareTo method is defined in the Comparable interface, and classes implementing it must provide their own implementation of this method.
  • The natural ordering is typically the order that makes sense for the class itself. For example, for strings, natural ordering is based on lexicographical order.
public class MyClass implements Comparable<MyClass> {
    private int value;

    // Constructor, getters, setters...

    @Override
    public int compareTo(MyClass other) {
        return Integer.compare(this.value, other.value);
    }
}
List<MyClass> myList = new ArrayList<>();
Collections.sort(myList);

Comparator Interface:

  • The Comparator interface is used when you want to define a custom ordering for objects that may not have a natural ordering or when you want to override the natural ordering.
  • The compare method is defined in the Comparator interface, and you can create multiple comparators for the same class to achieve different sorting criteria.
  • Comparators are particularly useful when you want to sort objects based on different attributes or in different orders without modifying the class itself.
public class MyComparator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass obj1, MyClass obj2) {
        return Integer.compare(obj1.getValue(), obj2.getValue());
    }
}

Usage

List<MyClass> myList = new ArrayList<>();
Collections.sort(myList, new MyComparator());