Comparable은 객체 클래스에서 구현되는 인터페이스입니다. 자연적인 정렬 순서를 정의하는 compareTo() 메소드를 하나 정의합니다.
Comparator는 compare(o1, o2) 메소드를 구현하는 별도의 인터페이스입니다. 클래스 코드를 변경하지 않고도 여러 가지 정렬 방법을 정의할 수 있게 해줍니다.
사용 시기:
예제:
// Comparable class Student implements Comparable<Student> { String name; int grade; public int compareTo(Student other) { return this.grade - other.grade; } } // Comparator Comparator<Student> byName = new Comparator<Student>() { public int compare(Student s1, Student s2) { return s1.name.compareTo(s2.name); } }; List<Student> students = ...; Collections.sort(students); // grade 기준으로 정렬 Collections.sort(students, byName); // name 기준으로 정렬
Comparable을 구현하지 않는 객체의 List를 Comparator 없이 정렬할 수 있을까요?
답변: 아니오. 클래스가 Comparable을 구현하지 않고 명시적으로 Comparator가 제공되지 않으면, 컬렉션을 정렬하려고 하면 ClassCastException이 발생합니다.
예제:
class Animal {} List<Animal> animals = ...; Collections.sort(animals); // Comparable이 없으면 ClassCastException
역사
재고 관리 프로젝트에서 Item 클래스에 대해 Comparable을 구현하는 것을 잊어버렸습니다. Collections.sort(items)를 통해 정렬을 시도했지만, compareTo() 메서드가 없어서 앱이 ClassCastException으로 자주 중단되었습니다.
역사
학생 점수 계산 서비스에서 개발자는 compareTo() 메서드에서만 grade 필드를 기준으로 비교를 구현했습니다. 나중에 이름과 생년월일로 정렬해야 할 필요성이 생겼지만, 클래스 코드가 보조 메서드로 확장되었고, 다양한 Comparator를 사용하여 compareTo()에서 복잡한 로직을 피할 수 있었습니다.
역사
온라인 주문 제품에서 주문을 날짜 기준으로 정렬하기 위해 람다 표현식을 이용한 Comparator를 사용하려 했지만, 날짜가 null일 수 있는 가능성을 고려하지 않았습니다. 그 결과, 배송 날짜가 없는 주문을 정렬할 때 예상치 못한 NullPointerException이 발생했습니다.