When you work with objects in Java, sometimes you need to sort them. Sorting numbers or strings is easy because Java already knows how to compare them. But what if you create your own class, like Student, Employee, or Product?
That’s where the Comparable interface comes in.
What is Comparable?
The Comparable interface is used to define the natural ordering of objects.
In simple words, it tells Java:
This is how objects of my class should be compared.
Where is it used?
It is part of the Java Collections Framework, and it works with methods like:
- Collections.sort()
- Arrays.sort()
The Comparable interface has only one method:
int compareTo(Object obj)
How it works:
- Returns 0 → both objects are equal
- Returns positive number → current object is greater
- Returns negative number → current object is smaller
Example 1:
Sorting Numbers (Default Behavior)
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5, 2, 8, 1);
Collections.sort(list);
System.out.println(list);
}
}
Output:
[1, 2, 5, 8]
Here, Integer already implements Comparable.
Example 2:
Custom Class (Student)
Now let’s create our own class and sort it.
Step 1: Create Class and Implement Comparable
class Student implements Comparable<Student> {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
public int compareTo(Student s) {
return this.id - s.id; // sorting by id
}
}
Step 2: Use It
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(3, "Ram"));
list.add(new Student(1, "John"));
list.add(new Student(2, "Arun"));
Collections.sort(list);
for(Student s : list) {
System.out.println(s.id + " " + s.name);
}
}
}
Output:
1 John
2 Arun
3 Ram
Sorting Based on Different Fields
If you want to sort by name instead of id:
public int compareTo(Student s) {
return this.name.compareTo(s.name);
}
Key Points to Remember
- Used for natural sorting
- Class must implement Comparable
- Override compareTo() method
- Works with sorting methods like Collections.sort()
Comparable vs Comparator (Quick Idea)
Comparable → inside the class (default sorting)
Comparator → outside the class (custom sorting)
Final Thought
Use Comparable when your class has a clear default way of sorting.
For example:
Students → by ID
Products → by price
Employees → by salary
If sorting changes frequently, then Comparator is better.
Top comments (0)