| Comparable | Comparator | |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T o) | compare(T o1, T o2) |
| Implement ở đâu | Bên trong class | Class riêng / lambda |
| Thứ tự | Natural ordering (1 cách) | Custom ordering (nhiều cách) |
| Sửa class gốc | Bắt buộc | Không cần |
java
// Comparable — natural ordering theo tuổi
class Employee implements Comparable<Employee> {
String name; int age;
@Override
public int compareTo(Employee o) { return Integer.compare(this.age, o.age); }
}
List<Employee> list = ...
Collections.sort(list); // dùng natural ordering
// Comparator — sort theo tên hoặc lương tuỳ ngữ cảnh
list.sort(Comparator.comparing(e -> e.name));
list.sort(Comparator.comparingInt((Employee e) -> e.age).reversed());Khi nào dùng cái nào:
- Comparable: class có thứ tự tự nhiên rõ ràng, dùng nhiều nơi (String, Integer, LocalDate đều implement).
- Comparator: cần nhiều cách sort, không sửa được class gốc (thư viện bên ngoài), hoặc sort theo logic tạm thời.
Comparator có nhiều helper Java 8+: comparing(), thenComparing(), reversed(), nullsFirst() — chain được.
Tóm lại: Comparable = "tôi tự biết mình đứng ở đâu"; Comparator = "ai đó bên ngoài quyết định thứ tự".