본문

Comparator와 Comparable(JAVA)

반응형

# Comparator와 Comparable

Comparator와 Comparable은 모두 인터페이스로 객체들을 정렬 또는 이진검색트리를 구성하는데 필요한 메서드를 정의하고 있다.
그래서 Comparable을 구현한 클래스는 정렬이 가능하다는 것을 의미한다.


- Comparable : 기본 정렬기준을 구현하는데 사용

- Comparator : 기본 정렬기준 외에 다른 기준으로 정려하고자할 때 사용(ex.역순 등..)

  (Comparator와 Comparable :: 내림차순 및 오름차순 정렬에 유용하게 사용된다.)


Source 01) ComparatorAndComparable.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package comparatorAndComparable;
 
import java.util.Comparator;
import java.util.TreeSet;
 
public class ComparatorAndComparable {
 
    public static void main(String[] args) {
        // TreeSet은 기본적으로 데이터를 정렬된 상태로 저장한다
        TreeSet set1 = new TreeSet();
        TreeSet set2 = new TreeSet(new Descending()); // TreeSet(Comparator c)
 
        int[] score = { 3050102040 };
 
        for (int i = 0; i < score.length; i++) {
            set1.add(new Integer(score[i]));    // [10, 20, 30, 40, 50]
            set2.add(new Integer(score[i]));
        }
 
        System.out.println("set1 : " + set1);
        System.out.println("set2 : " + set2);
 
    }
}
 
class Descending implements Comparator {
    public int compare(Object o1, Object o2) {
        if (o1 instanceof Comparable && o2 instanceof Comparable) {
            Comparable c1 = (Comparable) o1;
            Comparable c2 = (Comparable) o2;
            return c1.compareTo(c2) * -1;    // -1을 곱해서 기본 정렬방식의 역으로 변경한다.
        }                            // 또는 c2.compareTo(c1) 와 같이 순서를 바꿔도 된다.
        return -1;
    }
}
cs


Result)

1
2
set1 : [1020304050]
set2 : [5040302010]
cs



출처 및 참고자료 : JAVA의정석(남궁성 저)

반응형

공유

댓글