JAVA/포스팅

자바 컬렉션 프레임워크 Comparable

짜집퍼박사(짜박) 2023. 11. 18. 10:59

Comparable 인터페이스는 Java에서 제공하는 컬렉션 프레임워크에서 객체를 정렬할 때 사용되는 인터페이스입니다. 이 인터페이스를 구현하는 클래스는 정렬 가능한 클래스가 됩니다.

 

Comparable 인터페이스의 주요 메서드

 

public interface Comparable<T> {
    int compareTo(T o);
}

compareTo 메서드는 다음 규칙을 따릅니다.

 

- 이 객체가 다른 객체보다 작으면 음수를 반환.
- 이 객체가 다른 객체와 같으면 0을 반환.
- 이 객체가 다른 객체보다 크면 양수를 반환.

 

Comparable 사용 예제

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Student implements Comparable<Student> {
    private String name;
    private int age;

    // 생성자, 게터, 세터 등은 생략

    @Override
    public int compareTo(Student otherStudent) {
        // 이름을 기준으로 정렬
        return this.name.compareTo(otherStudent.getName());
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class ComparableExample {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("Alice", 20));
        studentList.add(new Student("Bob", 22));
        studentList.add(new Student("Charlie", 18));

        // Comparable을 구현한 클래스의 객체는 Collections.sort를 사용하여 정렬할 수 있다.
        Collections.sort(studentList);
        System.out.println("Sorted by name: " + studentList);
    }
}

위 예제에서 Student 클래스가 Comparable<Student>를 구현하고 있으며, compareTo 메서드를 재정의하여 이름을 기준으로 정렬하도록 구현했습니다. 그리고 Collections.sort를 사용하여 리스트를 정렬합니다.

Comparable을 구현하면 정렬이 필요한 클래스에서 Collections.sort 또는 배열의 Arrays.sort 등을 사용하여 객체를 정렬할 때 편리하게 사용할 수 있습니다.

 

With ChatGPT