[JAVA]Comparable과 Comparator 이해하기

jh5959·2025년 5월 17일

Java

목록 보기
3/9

정렬이란?

정렬은 두 대상을 어떤 기준으로 비교하여 자리바꿈 하는 것이다.
비교를 하기 위해서는 비교대상기준이 필요하다.

Comparable

Comparable은 기본 정렬 기준을 제공한다.
String, Integer 등은 Comparable를 구현했기 때문에 정렬 기준을 지정하지 않아도 된다.
compareTo 메서드를 통해 사전순이나 숫자 크기를 기준으로 정렬한다.

Comparator

Comparator은 외부에서 정렬 기준을 제공한다. 기본이 아닌 그 외 기준이다.
정렬 기준이 여러 개이거나 클래스 내부를 수정할 수 없을 때 외부에서 정렬 기준을 줘야할 때 사용한다.
compare(a,b)에서

  • a - b 는 오름차순
  • b - a 는 내림차순

a - b 에서

  • 양수면 a가 크다
  • 음수면 b가 크다
  • 0이면 둘이 같다

Comparable 예제

import java.util.*;

class Person implements Comparable {
    String name;

    Person(String name) {
        this.name = name;
    }

    public int compareTo(Object o) {
        if (o instanceof Person) {
            Person p = (Person) o;
            return this.name.compareTo(p.name); // 사전순 정렬
        }
        return -1;
    }

    public String toString() {
        return name;
    }
}

public class Test1 {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(new Person("Charlie"));
        list.add(new Person("Alice"));
        list.add(new Person("Bob"));

        Collections.sort(list); // compareTo() 사용

        Iterator it=list.iterator();
        while(it.hasNext())
        	System.out.println(it.next());
    }
}

실행결과:
Alice
Bob
Charlie

Comparator 예제

import java.util.*;

class Student {
    String name;
    int score;

    Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String toString() {
        return name + "(" + score + ")";
    }
}

class ScoreComparator implements Comparator {
    public int compare(Object o1, Object o2) {
        if (o1 instanceof Student && o2 instanceof Student) {
            Student s1 = (Student) o1;
            Student s2 = (Student) o2;
            return s1.score - s2.score; // 점수 오름차순
        }
        return -1;
    }
}

public class Test2 {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(new Student("Kim", 90));
        list.add(new Student("Lee", 75));
        list.add(new Student("Park", 85));

        Collections.sort(list, new ScoreComparator()); // Comparator 사용

        Iterator it=list.iterator();
        while(it.hasNext())
        	System.out.println(it.next());
    }
}

실행결과:
Lee(75)
Park(85)
Kim(90)

0개의 댓글