Comparable vs Comparator in Java
Comparable:
The
Comparable
interface is part of the Java language itself, and it is found in thejava.lang
package.When a class implements the
Comparable
interface, it means that instances of that class can be compared to each other for the purpose of natural ordering.The
Comparable
interface has one method,compareTo
, which takes another object of the same class as an argument and returns an integer value. This method should be implemented to specify the natural ordering of objects.The natural ordering is the default ordering for objects of the class when sorting without explicitly specifying a
Comparator
.
Example:
public class Person implements Comparable<Person> {
private String name;
private int age;
// Constructors, getters, setters...
@Override
public int compareTo(Person otherPerson) {
// Implement comparison logic based on age
return Integer.compare(this.age, otherPerson.age);
}
}
Comparator:
The
Comparator
interface is a more flexible way to define custom sorting orders for objects. It can be used to sort objects of classes that you cannot modify (e.g., classes from external libraries) or to define multiple sorting orders for a class.To use a
Comparator
, you create a separate class or lambda expression that implements theComparator
interface and provides the sorting logic.The
Comparator
interface has one method,compare
, which takes two objects of the class being sorted and returns an integer value to indicate their relative order.
Example:
// Define a Comparator for sorting Person objects by name
public class PersonNameComparator implements Comparator<Person> {
@Override
public int compare(Person person1, Person person2) {
return person1.getName().compareTo(person2.getName());
}
}
// Sorting using the PersonNameComparator
List<Person> people = new ArrayList<>();
// Add people to the list
Collections.sort(people, new PersonNameComparator());
In summary, Comparable
is used for defining the natural ordering of objects within a class, while Comparator
is used to define custom sorting orders for objects, either by implementing a separate comparator class or using lambda expressions. The choice between Comparable
and Comparator
depends on whether you have control over the class being sorted and whether you need to define multiple sorting orders.