What is Comparable vs Comparator in Java?

In Java, sorting of collections can be done using two main interfaces: Comparable and Comparator. Both of these interfaces play a crucial role in defining the order in which objects are sorted.

Comparable

The Comparable interface is used to define the natural ordering of objects. It is implemented by the class whose objects are to be compared. The class needs to override the compareTo() method, which compares the current object with the specified object.

Comparator

The Comparator interface, on the other hand, is used when you want to define multiple ways of sorting the objects. This interface is implemented in a separate class and defines the compare() method. It allows you to create different sorting strategies without changing the original class.

Example

// Example of Comparable class Employee implements Comparable { private String name; private int age; public Employee(String name, int age) { this.name = name; this.age = age; } // Overriding compareTo method public int compareTo(Employee e) { return this.age - e.age; // sorting by age } } // Example of Comparator class EmployeeNameComparator implements Comparator { public int compare(Employee e1, Employee e2) { return e1.name.compareTo(e2.name); // sorting by name } }

Comparable Comparator Java Sorting Collections