Comparable Interface in Java
In Java, the Comparable interface is used to compare objects and define their natural ordering.
Examples:
Comparing students based on marks
Comparing products based on price
Sorting strings alphabetically
Why Do We Need Comparable?
Primitive values like int or double can be compared easily.
But for custom objects like Student or Employee, Java does not know how to compare them by default.
So, we define the comparison logic using the Comparable interface.
Definition
public interface Comparable<T> {
int compareTo(T o);
}
The key method is compareTo().
*How compareTo() Works
*
Returns a negative value → current object is smaller
Returns 0 → both objects are equal
Returns a positive value → current object is greater
This is the basis for sorting.
Example: Sorting Students by Marks
import java.util.*;
class Student implements Comparable<Student> {
int marks;
String name;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
public int compareTo(Student s) {
return this.marks - s.marks; // ascending order
}
}
public class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student("A", 80));
list.add(new Student("B", 60));
list.add(new Student("C", 90));
Collections.sort(list);
for (Student s : list) {
System.out.println(s.name + " " + s.marks);
}
}
}
Output:
B 60
A 80
C 90
Key Points
Comparable defines natural (default) ordering
It is implemented inside the class
Collections.sort() automatically uses it
You must override compareTo()
Comparable vs Comparator
| Comparable | Comparator |
|---|---|
| Implemented inside the class | Implemented in a separate class |
| Only one sorting logic | Multiple sorting logics possible |
| Uses compareTo() | Uses compare() |
Simple Analogy
Comparable: the object decides how it should be compared
Comparator: an external logic decides how objects are compared
Final Line
The Comparable interface allows you to define a default sorting behavior for your objects.
Top comments (0)