Comparable VS Comparator

Rowan Lee·2024년 7월 24일

자바

목록 보기
2/10

자바의 내장 라이브러리의 sort 메서드를 그대로 사용하면서 규칙을 커스텀하기 위해서는 크게 두가지 방법이 있다.

Comparable

Comparable은 형용사인만큼 비교를 할 Class에 적용하는 interface이다.

class Student implements Comparable<Student> {
    int kor, eng, math;

    public Student(int kor, int eng, int math){
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }

    @Override
    public int compareTo(Student student) {
        if(this.kor > student.kor)
            return 1;
        else if(this.kor < student.kor)
            return -1;
        else
            return 0;
    }
};
// 만약 overflow가 생길 일이 없다면 밑과 같이 쓸 수 있다.
    @Override
    public int compareTo(Student student) {
        return this.kor = student.kor;
	}

이런식으로 사용한다. Comparable<T>을 구현해주면서 compareTo 메소드를 Ovveride 해주면 된다.

Comparator

Comparator은 명사인 만큼 비교를 해주는 별도의 interface이다.

Arrays.sort(students, new Comparator<Student>() {  
       @Override
       public int compare(Student a, Student b) {
           return a.kor - b.kor;
       }
 });
 
 // lambda표현을 사용하면 밑과 같다.
 Arrays.sort(students, (a, b) -> a.kor - b.kor);
 
 // 참고: 자바에서 lamdbda는 구현해할(static, default 제외) 메서드가 하나인 functional interface를 익명 객체로 만드는 것이다.

주의점

Comparable과 Comparator은 제네릭을 활용해 코딩되어 있으며 제네릭은 참조타입만을 취급한다. 즉 int[]와 같은 원시타입 배열은 별도로 자바가 오버로딩해둔 그대로 사용할 수 밖에 없다. 따라서 오름차순만 편하게 정렬 가능하다는 점 주의하자.

정말 구체적인 정렬이 필요하다면, 스트림을 활용해 박싱 -> 정렬 -> 언박싱 과정을 거쳐야한다.

비교정리

공통점: Class를 비교하는 방법에 대한 정의를 담아주는 인터페이스
차이점: 비교 방법을 비교 대상 Class 내부에 명시하기 vs 비교 방법을 비교 시점(Sort)에 명시하기

좀 더 구체적인 이해

https://st-lab.tistory.com/243
해당 블로그에 잘 정리되어 있으니 생각 안나면 읽어보자.

profile
CS/Software Engineer

0개의 댓글