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:
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.compareTo
method is defined in the Comparable
interface, and classes implementing it must provide their own implementation of this method.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:
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.compare
method is defined in the Comparator
interface, and you can create multiple comparators for the same class to achieve different sorting criteria.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());