05AM
[Java] Comparable vs Comparator 본문
`Comparable`과 `Comparator`는 객체의 정렬을 위해 사용되는 인터페이스입니다. 두 인터페이스는 서로 다른 방식으로 정렬 기준을 정의합니다.
🔷 `Comparable`
Comparable 인터페이스는 객체 자체에 기본 정렬 기준을 정의하고자 할 때 사용됩니다.
이 인터페이스를 구현하는 클래스는 자연 정렬(natural ordering)을 가지게 됩니다. 예를 들어, 숫자는 오름차순, 문자열은 사전순 등이 있습니다.
사용 상황:
- 클래스의 기본 정렬 순서를 정의하고 싶을 때
- 객체의 기본 정렬 기준이 하나만 있을 때
Comparable 인터페이스는 `compareTo` 메서드를 하나 가지고 있습니다.
➡️ 구조
public class ClassName implements Comparable<ClassName> {
@Override
public int compareTo(ClassName other) {
// 비교 로직
}
}
➡️ 사용 예제 1: 단일 속성 비교
public class Student implements Comparable<Student> {
private String name;
private int age;
@Override
public int compareTo(Student other) {
return Integer.compare(this.age, other.age); // 나이 순으로 정렬
}
}
➡️ 사용 예제 2: 복수 속성 비교
public class Student implements Comparable<Student> {
private String name;
private int age;
@Override
public int compareTo(Student other) {
// 먼저 나이를 비교
int ageComparison = Integer.compare(this.age, other.age);
if (ageComparison != 0) {
return ageComparison;
}
// 나이가 같으면 이름을 비교
return this.name.compareTo(other.name);
}
}
이렇게 구현된 Student 클래스는 `Collections.sort` 메서드를 사용할 때 나이와 이름순으로 정렬됩니다.
🔷 `Comparator`
Comparator 인터페이스는 객체의 비교 기준을 외부에서 정의하고자 할 때 사용됩니다. 이 인터페이스를 사용하면 여러 가지 비교 기준을 만들 수 있습니다.
사용 상황:
- 여러 가지 정렬 기준을 제공하고 싶을 때
- 기존 클래스의 소스를 수정할 수 없거나, 여러 기준으로 정렬할 필요가 있을 때
- 특정 상황에서 다른 정렬 기준을 적용하고 싶을 때
Comparator 인터페이스는 `compare` 메서드를 하나 가지고 있습니다.
➡️ 구조
public class ClassNameComparator implements Comparator<ClassName> {
@Override
public int compare(ClassName o1, ClassName o2) {
// 비교 로직
}
}
➡️ 사용 예제
public class Student {
private String name;
private int age;
}
public class StudentNameComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getName().compareTo(s2.getName()); // 이름 순으로 정렬
}
}
public class StudentAgeComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return Integer.compare(s1.getAge(), s2.getAge()); // 나이 순으로 정렬
}
}
이렇게 정의된 Comparator는 `Collections.sort` 메서드를 사용하여 이름순 혹은 나이순으로 정렬하는데 사용될 수 있습니다.
➡️ 사용 방법
List<Student> students = new ArrayList<>();
students.add(new Student("John", 25));
students.add(new Student("Jane", 22));
Collections.sort(students, new StudentNameComparator()); // 이름 순으로 정렬됨
Collections.sort(students, new StudentAgeComparator()); // 나이 순으로 정렬됨
🔷 요약
✅ Comparable: 객체 자체에 자연 정렬 기준을 정의하는 데 사용. `compareTo` 메서드를 구현.
✅ Comparator: 별도의 비교 기준을 정의하는 데 사용. `compare` 메서드를 구현.
'Programming Language > Java' 카테고리의 다른 글
[Java] collect(), Collectors, Collections 특징 정리 (0) | 2024.05.27 |
---|---|
[Java] Stream의 특징 (0) | 2024.05.27 |
[JAVA] StringBuilder와 StringBuffer를 사용하는 이유와 차이점 (1) | 2023.10.15 |
[Java] 키워드 정리 - this, super, static, final, 기본/참조 타입 (0) | 2023.04.21 |
Comments