정렬에 필요한 메서드를 정의한 인터페이스입니다. Comparable은 기본 정렬기준을 구현하는데 사용합니다.
public interface Comparable {
int compareTo(Object o); // 주어진 객체를 자신과 비교합니다.
}
Comparator은 기본 정렬기준 외에 다른 기준으로 정렬하고자 할 때 사용합니다.
public interface Comparator
int compare(Object o1, Object o2); // 두 객체를 비교
boolean equals(Object obj); // equals를 오버라이딩하라는 뜻
예제1
public final class Integer extends Number implements Comparable {
...
public int compareTo(Integer anotherInteger) {
int v1 = this.value;
int v2 = anotherInteger.value;
return (v1 < v2 ? -1 : (v1 == v2 ? 0 : 1));
}
...
}
예제2
import java.util.*;
class Ex11_7 {
public static void main(String[] args) {
String[] strArr = {"cat", "Dog", "lion", "tiger"};
Arrays.sort(strArr); // String의 Comparable 구현에 의해서 정렬됩니다.
System.out.println("strArr = " + Arrays.toString(strArr));
Arrays.sort(strArr, String.CASE_INSENSITIVE_ORDER); // 대소문자 구별 안함
System.out.println("strArr = " + Arrays.toString(strArr));
Arrays.sort(strArr, new Descending()); // 역순정렬
System.out.println("strArr = " + Arrays.toString(strArr));
}
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;
}
}
}
static void sort(Object[] a) : 객체 배열에 저장된 객체가 구현한 Comparable에 의해 정렬됩니다.
static void sort(Object[] a, Comparator c) : 지정한 Comparator에 의해 정렬됩니다.
public final class Integer extends Number implements Comparable {
...
public int compareTo(Object o) {
return compareTo((Integer)o);
}
public int compareTo(Integer anotherInteger) {
int thisVal = this.value;
int anotherVal = anotherInteger.value;
return (thisVal < anotherVal ? - 1 : (thisVal == anotherVal ? 0 : 1));
}
...
}