Junior — Middle
How are Comparator and Comparable interfaces implemented and used when working with collections in Java?
sobes.tech AI
Answer from AI
In Java, the interfaces Comparable and Comparator are used to define the order of objects when sorting collections.
- Comparable<T> — an interface implemented by the class of the object itself, defining the natural order. It contains the method
compareTo(T o).
Example:
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age); // sorting by age
}
}
- Comparator<T> — a separate interface that allows creating different sorting options without modifying the object class. It contains the method
compare(T o1, T o2).
Example:
Comparator<Person> nameComparator = new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name); // sorting by name
}
};
// or with a lambda expression
Comparator<Person> nameComparatorLambda = (p1, p2) -> p1.name.compareTo(p2.name);
Using with collections:
List<Person> people = ...;
Collections.sort(people); // uses Comparable
Collections.sort(people, nameComparator); // uses Comparator
Thus, Comparable sets the natural order for objects, and Comparator allows creating additional sorting methods.