Java Comparable Interface
Java Comparable Interface
The Comparable
interface allows you to define the natural ordering of objects so they can be sorted easily using built-in methods like Collections.sort()
or Arrays.sort()
.
It provides the compareTo()
method, which is used to define the natural ordering of objects. This method is used by sorting algorithms (like Collections.sort()
) to sort elements.
- Part of the
java.lang
package. - Used to define the natural ordering of objects.
- Contains a single method:
compareTo()
. - Implemented by a class whose objects need to be sorted.
- Used by sorting utilities such as
Collections.sort()
.
Uses of the Comparable Interface
The Comparable
interface is used to impose a natural ordering on the objects of each class that implements it. For example, if you have a list of custom Student
objects and you want to sort them by roll number, you can implement Comparable
in the Student
class and define the logic inside the compareTo()
method.
Comparable Interface Method
Method | Description |
---|---|
int compareTo(T o) |
Compares the current object with the specified object o for order. Returns a negative integer, zero, or a positive integer if the current object is less than, equal to, or greater than the specified object. |
Code Example
import java.util.*;
class Student implements Comparable<Student> {
int rollNo;
String name;
Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
// Defining natural ordering based on roll number
public int compareTo(Student s) {
return this.rollNo - s.rollNo;
}
public String toString() {
return rollNo + " - " + name;
}
}
public class ComparableExample {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(102, "Alice"));
list.add(new Student(101, "Bob"));
list.add(new Student(103, "Charlie"));
Collections.sort(list); // Sorts using compareTo()
for (Student s : list) {
System.out.println(s);
}
}
}