더북(TheBook)

public class Employee implements Comparable<Employee> {

    ...

    public int compareTo(Employee other) {

        return Double.compare(salary, other.salary);

    }

}


Note ≣

compare 메서드가 other.salary에 접근하는 것은 규칙에 들어맞는다. 자바의 메서드는 자신이 속한 클래스의 모든 객체에 있는 비공개 기능에 접근할 수 있다.


String 클래스는 자바 라이브러리에 들어 있는 100개 이상의 다른 클래스와 마찬가지로 Comparable 인터페이스를 구현한다. Arrays.sort 메서드는 Comparable 객체로 구성된 배열을 정렬한다.

String[ ] friends = { "Peter", "Paul", "Mary" };

Arrays.sort(friends); // friends ["Mary", "Paul", "Peter"]로 정렬된다.


Note ≣

이상하게도 Arrays.sort 메서드는 컴파일 시간에 인수가 Comparable 객체의 배열인지 검사하지 않는다. 그 대신 Comparable 인터페이스를 구현하지 않은 클래스 요소를 만나면 예외를 던진다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.