Sorting and Comparable
Java provides the Collections API, which includes interfaces and classes to work with collections of objects, one of them is for sorting collection.
Using Collections API to Sort a List
In Java, the Comparable
interface is used to define the natural ordering of objects. Objects of a class implementing the Comparable
interface can be compared and sorted based on a natural order defined by the class itself. This interface contains a single method: compareTo(Object obj)
. Here's a detailed explanation along with an example code:
1. Comparable Interface:
compareTo(Object obj)
Method:This method compares the current object with the specified object for order.
It returns a negative integer, zero, or a positive integer if the current object is less than, equal to, or greater than the specified object, respectively.
Example: Implementing Comparable for Sorting Custom Objects
Suppose you have a Person
class:
In this example, the Person
class implements the Comparable
interface. The compareTo()
method compares Person
objects based on their ages.
2. Usage in Sorting using Comparable:
You can use the compareTo()
method to sort objects of the class implementing the Comparable
interface using sorting methods like Collections.sort()
.
Example: Sorting a List of Persons
Output:
In this example, the Collections.sort()
method sorts the list of Person
objects based on their ages due to the natural ordering defined by the compareTo()
method in the Person
class.
Explanation:
Implementing the
Comparable
interface allows objects of a class to be compared and sorted based on the defined natural order.The
compareTo()
method returns a negative value if the current object is less than the specified object, zero if they are equal, and a positive value if the current object is greater.Sorting methods like
Collections.sort()
use thecompareTo()
method for sorting objects of the implementing class.
Last updated