Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khác biệt giữa Comparable và Comparator trong Java

Cả hai đều là interface dùng để sắp xếp collection. Comparable trong java.lang, Comparator trong java.util.

Bảng so sánh chi tiết

STT Tiêu chí Comparable Comparator
1 Method compareTo(T o) - so sánh "this" với object khác compare(T o1, T o2) - so sánh 2 object bất kỳ
2 Cách sắp xếp Collections.sort(List) Collections.sort(List, Comparator)
3 Chuỗi sắp xếp Chỉ 1 chuỗi sắp xếp tự nhiên (natural ordering) Nhiều chuỗi sắp xếp khác nhau (multiple strategies)
4 Package java.lang java.util

Ví dụ Comparable (Natural Ordering)

public class Laptop implements Comparable<Laptop> {
    String name;
    int ram;
    int price;
    
    // constructor, getters, setters...
    
    @Override
    public int compareTo(Laptop o) {
        return Integer.compare(this.ram, o.getRam()); // Sắp xếp theo RAM tăng dần
    }
}

// Sử dụng:
List<Laptop> list = new ArrayList<>();
list.add(new Laptop("HCL", 16, 800));
list.add(new Laptop("Apple", 8, 100));
list.add(new Laptop("Dell", 4, 600));
Collections.sort(list); // Tự dùng compareTo
// Kết quả: Dell(4), Apple(8), HCL(16)

Ví dụ Comparator (Multiple Strategies)

// Comparator riêng biệt (khuyên dùng class riêng hoặc lambda)
Comparator<Laptop> byName = (o1, o2) -> o1.getName().compareTo(o2.getName());
Comparator<Laptop> byPrice = (o1, o2) -> Integer.compare(o1.getPrice(), o2.getPrice());
Comparator<Laptop> byRamDesc = (o1, o2) -> Integer.compare(o2.getRam(), o1.getRam());

// Sử dụng:
Collections.sort(laptopList, byName);    // Sắp xếp theo tên
Collections.sort(laptopList, byPrice);   // Sắp xếp theo giá
Collections.sort(laptopList, byRamDesc); // Sắp xếp RAM giảm dần

Khi nào dùng cái nào?

  • Comparable: Khi class có một thứ tự tự nhiên duy nhất (VD: String, Integer, Date, Employee theo ID).
  • Comparator: Khi cần nhiều cách sắp xếp, hoặc không thể sửa class gốc (class final, library), hoặc sắp xếp theo tiêu chí phức tạp.

Java 8+ Enhancement

Comparator có thêm nhiều method tiện ích: comparing(), thenComparing(), reversed(), nullsFirst()/nullsLast() giúp chain sắp xếp rất linh hoạt.