| 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 |
// 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ự".
| Comparable | Comparator | |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T o) | compare(T o1, T o2) |
| Where implemented | Inside the class | Separate class / lambda |
| Ordering | Natural (one way) | Custom (many ways) |
| Modify original class | Required | Not needed |
// Comparable — natural ordering by age
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); // uses natural ordering
// Comparator — sort by name or salary depending on context
list.sort(Comparator.comparing(e -> e.name));
list.sort(Comparator.comparingInt((Employee e) -> e.age).reversed());When to use which:
- Comparable: the class has a clear, widely-used natural order; built-in types like String, Integer, LocalDate already implement it.
- Comparator: you need multiple sort orders, cannot modify the original class (third-party library), or the sorting logic is context-specific.
Java 8+ Comparator helpers chain cleanly: comparing(), thenComparing(), reversed(), nullsFirst().
Bottom line: Comparable = "I know my own order"; Comparator = "someone outside decides the order".