Java에서 객체를 정렬하거나 자료 구조(예: 우선순위 큐, 트리 세트 등)에 넣을 때, 객체의 비교 방법을 정의해야 할 때가 있다. 이를 위해 Java에서는 Comparable 인터페이스를 제공한다. 이 글에서는 Element 클래스를 예로 들어 Comparable 인터페이스의 구현 방법에 대해 알아보려한다.
Element 클래스 개요Element 클래스는 두 개의 필드를 가지고 있다: index와 distance. 이 클래스의 인스턴스는 어떤 요소의 인덱스와, 특정 기준점으로부터의 거리를 나타낸다.
class Element {
int index;
int distance;
Element(int index, int distance) {
this.index = index;
this.distance = distance;
}
}
Comparable 인터페이스 구현Element 클래스는 Comparable<Element> 인터페이스를 구현한다. 이는 Element 인스턴스들을 서로 비교할 수 있게 해주며, 주로 정렬이나 탐색 알고리즘에서 유용하게 사용된다.
@Override
public int compareTo(Element o) {
return Integer.compare(this.distance, o.distance);
}
compareTo 메서드는 객체 자신(this)과 다른 객체(o)를 비교한다. 여기서는 distance 필드를 기준으로 비교를 수행한다.
this.distance < o.distance: 메서드는 -1을 반환한다. 이는 객체 this가 객체 o보다 "작다"는 것을 의미한다this.distance > o.distance: 메서드는 1을 반환한다. 이는 객체 this가 객체 o보다 "크다"는 것을 의미한다.this.distance == o.distance: 메서드는 0을 반환한다. 이는 두 객체가 같다는 것을 의미한다.Element 클래스의 인스턴스들을 배열이나 리스트에 저장하고, Collections.sort 또는 Arrays.sort 메서드를 사용하여 distance 값을 기준으로 정렬할 수 있다.
List<Element> elements = new ArrayList<>();
elements.add(new Element(0, 5));
elements.add(new Element(1, 2));
elements.add(new Element(2, 3));
Collections.sort(elements);
이 코드는 elements 리스트를 distance 값에 따라 오름차순으로 정렬한다
Comparable 인터페이스를 구현함으로써, 사용자 정의 클래스의 인스턴스들을 원하는 기준에 따라 쉽게 정렬할 수 있다.