Comparable과 Comparator를 사용하는 방법을 비교한다.Comparable 인터페이스는 객체의 순서를 정의하는데 사용된다.compareTo 메소드를 override해야한다.public class Student implements Comparable<Student> {
private String name;
private int age;
// 생성자, getter, setter 생략...
@Override
public int compareTo(Student otherStudent) {
return this.name.compareTo(otherStudent.getName());
}
}
Comparable인터페이스를 구현한 Student클래스의 인스턴스들은 Arrays.sort()나 Collecitons.sort()메서드를 호출하면 이름순으로 정렬된다.Comparator 인터페이스 또한 객체의 순서를 변경하거나, 특정 속성에 따라 정렬하고 싶을 때 사용된다.익명 클래스로 사용된다.Comparator<Student> comparator = new Comparator<>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getName().compareTo(s2.getName());
}
};
List<Student> students = new ArrayList<>();
// 학생들 추가...
Collections.sort(students, comparator);
// java 8이후 람다식
List<Student> students = new ArrayList<>();
// 학생들 추가...
students.sort((s1, s2) -> s1.getName().compareTo(s2.getName()));
Comparable은 객체의 순서를 미리 정의하여 사용하는데 반해, Comparator는 특정 속성에 따라 객체를 정렬할 수 있다.compareTo()를 구현할 때 어떤 순서로 정렬되는지 헷갈릴 때가 종종 있다.@Override
public int compareTo(Student other) {
if (this.age > other.age) {
return 1;
} else if (this.age == other.age) {
return 0;
} else if (this.age < other.age) {
return -1;
}
}
underflow나overflow도 방지할 수 있다.Comparator를 구현하여 사용하는 경우는 앞과 비슷하게 사용할 수 있지만 람다식을 사용하면 여로 조건으로 정렬하는 경우에도 더 쉽게 표현할 수도 있다.// 이름 순으로 정렬, 이름이 같다면 나이가 많은 순서부터 정렬
Comparator<Person> comparator = Comparator
.comparing(Person::getName)
.thenComparing(Person::getAge, Comparator.reverseOrder());
comparing(비교대상)을 사용하여 정렬할 수 있고, 만약 같을 때 추가 조건이 있으면 thenComparing(비교대상)을 사용해 정렬할 수 있다.sort()처럼 인수에 Comparator.reverseOrder()를 추가하면 내림차순으로 정렬할 수 있다.Java 공식 문서 - Arrays, Collections, Comparable, Comparator