🎯 1. Why Do We Need Custom Sorting?

Java knows how to sort numbers & strings, but not your custom objects.

Example:

List<Student> list =newArrayList<>();
Collections.sort(list);// ❌ Java doesn't know HOW to sort Students

So we tell Java the sorting rule using:


2. Comparable vs Comparator (Big Picture)

Feature Comparable Comparator
Package java.lang java.util
Method compareTo() compare()
Sorting logic Inside the class Outside the class
Sorts by One natural order Multiple custom orders
Modify class? ✔ Yes ❌ No

🔵 COMPARABLE – Natural Ordering


🎯 3. What is Comparable?

Comparable defines the default (natural) sorting order of objects.

Implemented by the class itself.


🧱 4. Comparable Syntax

classStudentimplementsComparable<Student> {

int marks;

@Override
publicintcompareTo(Student s) {
returnthis.marks - s.marks;
    }
}