Comparable : 객체의 자연 순서를 정의하는데 사용된다.
- 구현 시 객체를 정렬할 수 있는 방법을 제공한다.
- 하나의 메서드 compareTo를 선언
Comparable 인터페이스 구현
- 클래스 선언시 'Comparable<T>' 인터페이스를 구현한다. 여기서 T는 클래스의 타입.
- 'compareTo' 메서드를 오버라이드하여 두 객체를 비교하는 로직을 작성한다.
compareTo 메서드의 반환값
- 음수 : 현재 객체가 비교 객체보다 작음
- 양수 : 현재 객체가 비교 객체보다 큼
- 0 : 두 객체가 같음
예제
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person other) {
// 나이를 기준으로 비교
return Integer.compare(this.age, other.age); //밑에 따로 설명
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
Collections.sort(people);
for (Person person : people) {
System.out.println(person);
}
}
}
Collections.sort()
- comparable 인터페이스를 구현한 객체들의 리스트를 정렬
- 'List<String>', 'List<Integer>' 또는 'Comparable' 인터페이스를 구현한 사용자 정의 객체 리스트를 정렬할 수 있다.
- List 타입들은 Comparable 인터페이스를 구현하고 있으므로 List 타입 또한 compareTo 메서드를 기준으로 정렬된다.
public static <T extends Comparable<? super T>> void sort(List<T> list)
Integer.compare(a,b)
- 두 정수 값을 비교하여 결과를 반환하는 메서드
- a < b : 음수 반환
- a > b : 양수 반환
- a == b : 0 반환
Integer.compare() 을 사용하지 않고 아래와 같이 직접 구현할 수 도 있다.
@Override
public int compareTo(Person other){
if(this.age < other.age){
return -1;
} else if (this.age > other.age){
return 1;
} else {
return 0;
}
}