Comparable Interface in Java Collections :
What is it?
Comparable is a Java interface in java.lang with a single method:
Ex:
public interface Comparable<T> {
int compareTo(T other);
}
It defines the natural ordering of objects of a class. When a class implements Comparable, it's saying "I know how to compare myself to another object of my type."
compareTo return values:
Return Value - Meaning
negative - this < other
0 - this== other
positive - this > other
Example:
Product pen = new Product("Pen", 10.0);
Product bag = new Product("Bag", 50.0);
Product book = new Product("Book", 10.0); // same price as pen
System.out.println(pen.compareTo(bag)); // negative → pen < bag
System.out.println(bag.compareTo(pen)); // positive → bag > pen
System.out.println(pen.compareTo(book)); // 0 → equal price
Result - Meaning
negative - pen is cheaper than bag
0 - pen and book cost the same
positive - bag is more expensive than pen
Why use it?
Without Comparable, Java's sorting and ordering mechanisms have no idea how to rank your custom objects.
Implementing it lets you use:
- Collections.sort(list)
- Arrays.sort(array)
- TreeSet / TreeMap (automatically sorted)
- PriorityQueue (min-heap by default)
When to use it?
Use Comparable when your class has one obvious, default ordering that makes sense intrinsically — like a Student sorted by roll number, or a Product by price.
class Student implements Comparable<Student> {
String name;
int rollNo;
Student(String name, int rollNo) {
this.name = name;
this.rollNo = rollNo;
}
@Override
public int compareTo(Student other) {
return this.rollNo - other.rollNo; // Natural order: ascending by rollNo
}
@Override
public String toString() {
return name + "(" + rollNo + ")";
}
}
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 3));
students.add(new Student("Bob", 1));
students.add(new Student("Carol", 2));
Collections.sort(students); // Uses compareTo internally
System.out.println(students); // [Bob(1), Carol(2), Alice(3)]
// Works with TreeSet too
TreeSet<Student> set = new TreeSet<>(students);
System.out.println(set); // [Bob(1), Carol(2), Alice(3)]
}
}
Top comments (0)