본문 바로가기
JAVA/Java

Comparable 인터페이스

by KkingKkang 2023. 11. 16.

 Java의 Comparable 인터페이스는 객체들의 정렬(sorting)을 위해 사용됩니다. 

- Comparable 인터페이스는 compareTo() 메서드 하나만 정의되어 있습니다.

- 이 인터페이스를 구현한 클래스는 서로 그 객체들을 비교할 수 있습니다.

- compareTo() 메서드는 인자로 전달된 객체와 자신을 비교해서 정수 값을 리턴합니다.

- 반환값이 0이면 두 객체가 같다는 것이고, 음수이면 자신이 앞에 오고, 양수이면 인자로 받은 객체가 앞에 오는 것입니다. 

- 이를 통해 객체들을 정렬할 수 있습니다.

- 주로 Wrapper 클래스(Integer, Double 등), String, Date와 같은 클래스가 Comparable을 구현하고 있습니다.

- Collections.sort()를 사용할 때 이 인터페이스를 구현했는지 여부에 따라 정렬 여부가 결정됩니다.

 

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

class Student implements Comparable<Student> {

  private int id;
  private String name;

  public Student(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public int compareTo(Student otherStudent) {
    return this.id - otherStudent.id; 
  }
}

public class Main {

  public static void main(String[] args) {
    List<Student> students = new ArrayList<>();
    students.add(new Student(3, "John")); 
    students.add(new Student(1, "Alice"));
    students.add(new Student(2, "Bob"));

    Collections.sort(students);

    for(Student student: students) {
      System.out.println(student.name); 
    }
  }
}


이 예제에서 Student 클래스는 Comparable을 구현하고 있습니다. 
compareTo() 메서드를 통해 학생 id를 기준으로 오름차순 정렬하도록 했습니다.
main에서 List를 정렬하고 출력하면 id 순서대로 이름이 출력됩니다.

 

 

내림차순으로 정렬하려면 compareTo() 메서드에서 대소관계를 반대로 하면 됩니다.

public int compareTo(Student otherStudent) {
  return this.id - otherStudent.id;
}

예를 들어 위 코드에서 id 오름차순 정렬을 했다면,

내림차순으로 정렬하려면 아래와 같이 다른 Student의 id와 자신의 id를 빼주면 됩니다.

public int compareTo(Student otherStudent) {
  return otherStudent.id - this.id; 
}



다른 방법은 Comparator 인터페이스를 사용하는 것입니다.

Collections.sort(students, new Comparator<Student>() {
  public int compare(Student s1, Student s2) {
    return s2.id - s1.id; // 내림차순
  }  
});



Comparator를 사용하면 기존의 compareTo() 메서드는 그대로 두고 별도로 정렬 기준을 지정할 수 있습니다.

반응형

'JAVA > Java' 카테고리의 다른 글

Doubly Linked List 이중 연결 리스트  (0) 2023.10.24
ArrayList  (0) 2023.10.23
배열 인덱스 범위 초과 예외 처리  (1) 2023.10.18
JAVA stream  (2) 2023.10.18
DAO생성에서 확인하고 넘어갈 개념 4가지  (0) 2023.07.17

댓글