Comparable vs Comparator

HOSEON YOO·2023년 9월 10일
1

개요

  • JDK 1.8

오늘 풀지 못했던 알고리즘 문제가 사용자 정의 객체에 Comparable을 구현해서 푸는 문제였다. Comparable과 Comparator에 대해 아직도 혼란스러워해서 다시 한번 공부하면서 정리해보기로 한다.

Comparable

Comparable은 인터페이스로 추상메서드 compareTo()를 포함하고 있다. 공식문서에서는 "자기 자신과 매개변수 객체를 비교한다." 라고 표기되어있다.

Student.java

public class Student implements Comparable<Student> {
    public int score;

    public Student(int score) {
        this.score = score;
    }

    @Override
    public int compareTo(Student o) {
        return this.score - o.score;
    }
}

ComparableTest.java

public class ComparableTest {
    public static void main(String[] args) {
        Student student1 = new Student(10);
        Student student2 = new Student(20);
        int result = student1.compareTo(student2);
        if (result > 0) {
            System.out.println("student1 > student2");
        } else if (result == 0) {
            System.out.println("student1 == student2");
        } else {
            System.out.println("student1 < student2");
        }
    }
}

Comparator

Comparator은 인터페이스로 추상메서드 compare()를 포함하고 있다. 공식문서에서는 "두개의 매개변수 객체를 비교한다." 라고 표기되어있다.

Student.java

public class Student implements Comparator<Student> {
    public int score;

    public Student(int score) {
        this.score = score;
    }

    @Override
    public int compare(Student o1, Student o2) {
        return o1.score - o2.score;
    }
}

ComparatorTest.java

public class ComparatorTest {
    public static void main(String[] args) {
        Student student1 = new Student(10);
        Student student2 = new Student(20);
        int result = student1.compare(student1, student2);
        if (result > 0) {
            System.out.println("student1 > student2");
        } else if (result == 0) {
            System.out.println("student1 == student2");
        } else {
            System.out.println("student1 < student2");
        }
    }
}

참고자료

profile
안녕하세요~ 👋, 대한민국 개발자 유호선입니다.

0개의 댓글