Collections Framework · Lesson 86 of 150
Comparable
Comparable is an interface that lets you define the "natural" sorting order for objects of your own class, by implementing its single method, compareTo().
01What is Comparable?
Comparable is an interface that lets you define the "natural" sorting order for objects of your own class, by implementing its single method, compareTo().
02Why is it used?
When you have a custom class (like Student) and want collections of its objects (like a List<Student> or TreeSet<Student>) to sort automatically, you implement Comparable to define exactly how two objects of that class should be compared.
03Real-Life Example
Think of defining a general house rule: "Always arrange books by their title, alphabetically." Once this rule is set, any bookshelf using it automatically knows how to arrange the books, without needing separate instructions each time.
04Syntax
javaclass ClassName implements Comparable<ClassName> { public int compareTo(ClassName other) { // comparison logic } }
05Example Program
javaclass Student implements Comparable<Student> { String name; int marks; Student(String name, int marks) { this.name = name; this.marks = marks; } public int compareTo(Student other) { return this.marks - other.marks; } } import java.util.*; public class ComparableDemo { public static void main(String[] args) { List<Student> students = new ArrayList<>(); students.add(new Student("Riya", 85)); students.add(new Student("Aman", 70)); Collections.sort(students); for (Student s : students) { System.out.println(s.name + ": " + s.marks); } } }
Output:
Aman: 70
Riya: 8506Key Points to Remember
Comparabledefines only one, single "natural" sorting order per class.- The
compareTo()method should return a negative number, zero, or a positive number, depending on the comparison result. - Use
Comparator(next topic) when you need multiple, different sorting orders for the same class.