참고자료:
https://docs.oracle.com/javase/8/docs/api/
이 인터페이스를 구현하는 클래스의 객체를 정렬하게 해준다.
compareTo 메소드가 기본적인 비교 메소드이다.
이 인터페이스를 구현하는 객체의 리스트는 Collections.sort를 통해 자동적으로 정렬될 수 있다.
e1.compareTo(e2) == 0이 클래스 C의 모든 객체 e1과 e2에 대해서 같은 값을 가질 때 equals와 같은 기능을 하게 된다. 필수는 아니지만 compareTo를 오버라이드 할 경우 equals와 같은 기능을 하도록 구현하는 것을 권장한다.
주의할 것: null은 어떤 클래스의 인스턴스도 아니므로 e.compareTo(null)은 NullPointerException을 발생시킨다.
int compareTo(T o)
리턴값
호출한 객체가 o(매개변수) 객체보다 작거나, 같거나, 클 때 각각 음수, 0, 양수 값을 리턴한다.
int compare(T o1, T o2)
리턴값
o1이 o2보다 작거나, 같거나, 클 때 각각 음수, 0, 양수 값을 리턴한다.
두 인터페이스 모두 사용자 정의 객체간의 비교가 필요할 때 사용한다.
Comparable 인터페이스를 기반으로 비교 메소드를 정의하기 위해서는 compareTo 메소드를 override 해야 한다. 마찬가지로 Comparator 인터페이스를 사용하기 위해서는 compare 메소드를 override 해야한다.
둘의 차이는 Comparable 인터페이스는 자기 자신과 입력값의 비교라면 Comparator는 자기 자신과 무관하게 입력받은 두 인자값을 비교한다는 점이다.
에러 메시지를 한 줄 요약하면:
Collections.sort(List<T>)는 T가Comparable을 구현한 클래스일 때만 사용할 수 있는데,
당신의Number클래스는Comparable이 아니라Comparator를 구현했기 때문에 에러가 난 것입니다.
당신의 Number 클래스 선언을 다시 보겠습니다:
public static class Number implements Comparator<Number> { ... }
이렇게 하면 Number는 비교 대상이 아니라 비교자(정렬 기준 제공자) 역할을 하게 됩니다.
그런데 아래처럼 Collections.sort(newRows[i])을 호출했죠?
Collections.sort(newRows[i]); // ❌ 컴파일 에러
이건 리스트 안의 요소들이 스스로 정렬 기준을 제공해야 (Comparable 구현해야) 가능한 방식입니다.
Number가 Comparable<Number>를 구현하게 수정public static class Number implements Comparable<Number> {
int value;
int quantity;
Number(int value, int quantity) {
this.value = value;
this.quantity = quantity;
}
@Override
public int compareTo(Number other) {
if (this.quantity != other.quantity) {
return Integer.compare(this.quantity, other.quantity);
}
return Integer.compare(this.value, other.value);
}
}
그리고 기존 정렬 코드는 그대로 유지합니다:
Collections.sort(newRows[i]); // ✅ 이제 잘 작동함
Comparator<Number>를 별도로 만들고 sort 시에 인자로 넘기기public static class Number {
int value;
int quantity;
Number(int value, int quantity) {
this.value = value;
this.quantity = quantity;
}
}
public static class NumberComparator implements Comparator<Number> {
@Override
public int compare(Number n1, Number n2) {
if (n1.quantity != n2.quantity) {
return Integer.compare(n1.quantity, n2.quantity);
}
return Integer.compare(n1.value, n2.value);
}
}
그리고 정렬할 때:
Collections.sort(newRows[i], new NumberComparator());
Number가 스스로 정렬 기준을 가지는 게 자연스럽다면 → 방법 1 (Comparable)을 추천합니다.
질문에 주신 코드는 분명히 Number 인스턴스들이 정렬되는 입장이므로 Comparable<Number> 구현이 더 적합합니다.
(지금처럼 Comparator<Number>를 구현하는 건 정렬 기준을 따로 전달하려는 경우에 쓰는 방식입니다.)