Comparable interface in Java is used to define the natural ordering of objects. It allows objects to be compared and sorted easily.
In this chapter, you will learn about the Comparable interface, how it works, and how to use it to sort objects.
Comparable is an interface in the java.lang package that is used to compare objects of a class. It provides the compareTo() method, which defines the natural ordering of objects. By implementing this interface, a class can specify how its objects should be sorted.
The compareTo() method is used to compare the current object with another object.
The syntax of the method is as follows:
Here,
The Comparable interface is used to sort:
The Collections.sort() method is used to sort elements of a List, and the elements must implement the Comparable interface.
Note: String and Wrapper classes already implement Comparable, so they can be sorted directly.
This example demonstrates how to sort objects based on age using the Comparable interface.
Output:
105 Jai 21 101 Vijay 23 106 Ajay 27
This example demonstrates how to sort objects in reverse order using the Comparable interface.
Output:
106 Ajay 27 101 Vijay 23 105 Jai 21
The Comparable interface provides a simple way to define the natural ordering of objects within a class. It requires minimal code and is widely used with collections like ArrayList, TreeSet, and TreeMap for sorting.
Comparable allows sorting based on only one attribute at a time. If you need multiple sorting criteria (e.g., sort by name, then by age), Comparable is not suitable, and Comparator should be used instead.
Comparable is used for defining the natural ordering inside the class, whereas Comparator is used to define multiple sorting orders externally without modifying the class.
We request you to subscribe our newsletter for upcoming updates.