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:
| 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 defines the default (natural) sorting order of objects.
Implemented by the class itself.
classStudentimplementsComparable<Student> {
int marks;
@Override
publicintcompareTo(Student s) {
returnthis.marks - s.marks;
}
}