
어지럽게 널브러진 데이터를 나열하는 것은 꽤나 중요하다.
자바에서는 데이터 정렬을 위해 해야만 하는 작업이 있다.
Comparable과 Comparator에 대해 알아보자.

정렬을 위해서는 정렬할 데이터들과 정렬 기준이 필요하다.
자바에서는 정렬 기준을 만들기 위해 Comparator 인터페이스를 구현해야 하며,
compare 메서드를 오버라이딩해야 한다.
class NumberComparator implements Comparator<Integer> {
@Override
public int compare(Integer i1, Integer i2) {
// 메서드 바디
}
}
정렬할 데이터와 함께 구현한 Comparator을 파라미터로 전달하여
Arrays.sort() 메서드를 수행하면 데이터를 정렬할 수 있다.
Arrays.sort(data, new NumberComparator());
Arrays.sort(data, new NumberComparator().reversed()); // ** 반대로 정렬 **

자바가 제공하는 참조형을 제외하고,
직접 만든 객체에는 복잡한 정렬 기준을 어떻게 적용할 수 있을까?
이 경우에는 정렬할 객체에 Comparable 인터페이스를 구현하고,
compareTo() 메서드를 오버라이딩하면 된다.
class Student implements Comparable<Student> {
int id;
String name;
int age;
@Override
public int compareTo(Student student) {
// 메서드 바디
}
}
compareTo() 메서드 내부에서 정렬 기준을 직접 설정하여 구현할 수 있다.
예를 들어 학생의 경우 학번을 기준으로 정렬하고,
우연히 학번이 동일하다면 나이를 기준으로 추가로 정렬하도록 구현할 수 있다.
Student[] students = {student1, student2, student3};
Arrays.sort(students);
정렬할 객체에 Comparable 인터페이스를 구현한 경우,
정렬 기준인 Comparator을 파라미터로 전달하지 않아도 compareTo() 메서드에 따라 정렬할 수 있다.
Arrays.sort(students, new StudentComparator());
물론 사용자 정의 객체 역시 Comparator을 생성해서 파라미터로 전달할 수 있다.
Comparator나 Comparable 인터페이스를 구현하지 않고 정렬을 시도하는 경우 런타임 에러가 발생한다.

배열리스트, 세트 등 자바 자료구조도 정렬이 가능하다.
List<Student> studentList = new ArrayList<>();
studentList.sort();
studentList.sort(new StudentComparator());
Tree<Student> studentTree = new TreeSet<>(); // ** Tree는 기본으로 정렬 기능 장착 **
Tree<Student> studentTree2 = new TreeSet<>(new StudentComparator());
Collections.sort(studentList); // ** Collections 유틸 **
정렬을 위해 수행해야 하는 인터페이스 구현에 대해 알아봤다.
정렬이 필요한 경우 Comparator과 Comparable을 잊지 말고 구현하자.