Comparable interface is used to define the natural ordering of objects. In other words, it is used when you want to compare an object with another object of the same type. To implement the Comparable interface, you need to define a compareTo() method that takes an object of the same type and returns an integer value that indicates the order of the objects.
Feature | Comparable | Comparator |
---|---|---|
Interface | java.lang.Comparable<T> | java.util.Comparator<T> |
Purpose | Define natural ordering | Define custom ordering |
Method to implement | int compareTo(T o) | int compare(T o1, T o2) |
Object comparison | Objects of the same type | Objects of different types |
Usage | Arrays.sort() and Collections.sort() | Collections.sort() and custom sorting |
Single or multiple | Single instance per object | Multiple instances |
Inherited by subclasses | Yes | No |
To summarize, the main difference between Comparable and Comparator is that Comparable is used to define the natural ordering of objects, whereas Comparator is used to define a custom ordering of objects. The Comparable interface defines a compareTo() method that is used to compare objects of the same type, while the Comparator interface defines a compare() method that is used to compare objects of different types.