본문 바로가기
Work/Java

[Java] 객체 배열의 정렬 Comparator, Comparable 정리

이전글에서 1차원배열의 오름차순 , 내림차순 정렬과

2차원 배열에서 Comparator를 구현하는 예제등을 알아보았다.

 

이번에는 사용자가 만든 클래스를 배열의 타입으로 가지는 객체배열의 정렬을 해보자.

객체 정렬은  Comparable , Comparator 모두 사용이 가능하지만, 

구현 방식에 차이가 있다.

 

1. Comparator 

Comparator 는 이전글에도 보았다시피,

Comparator compare 메소드를 재정의하여 Arrays.sort , Collections.sort 등에 인자로 사용된다

Comparator의 특징

  • sort마다 원하는 방식으로 자유롭게 정렬하기 좋다.
  • 구현체를 선언해두고 재사용도 할 수 있다.
  • sort에서 람다식으로 비교적 짧게 축약사용이 가능하다.

 

2. Comparable 

Comparable은 사용자가 클래스를 만들때, 상속받아 implements 하는 방식으로 구현되어 사용한다.

해당 클래스를 타입으로 가지는 배열이나 컬렉션을 단순 sort하는 경우,

implements 했던 내용을 기반으로 정렬된다.

 

Comparable의 특징

  • 클래스가 상속받아서 compareTo 메소드를 구현함
  • 해당 객체 배열은 기본적으로 compareTo 구현방식대로 정렬됨.
  • 모든 값 클래스, 열거 타입은 Comparable이 구현되어져 있으므로 sort사용이 가능한것이다.
  • 정렬기준을 바꾸는게 어렵다.
  • Collections.reverseOrder() 사용이 가능하다.

 

예제 코드


import java.util.Arrays;
import java.util.Comparator;

public class ClassSort {
    public static void main(String[] args) {
        Student[] arr = new Student[5];
        String[] name = {"Bang","Ann","Choi","Lee","Dong"};
        for(int i=0;i<5;i++)
            arr[i] = new Student(name[i],i+1);
        System.out.println("--- Comparable 사용 이름순 정렬 ---");
        Arrays.sort(arr);
        for (Student student : arr)
            System.out.println("student.name = " + student.name + "\tstudent.sno = "+ student.sno);

        System.out.println("--- Comparator 사용 번호순 정렬 ---");
        Arrays.sort(arr, new Comparator<Student>() { // lambda : Arrays.sort(arr, (o1, o2) -> o1.sno - o2.sno);
            @Override
            public int compare(Student o1, Student o2) {
                return o1.sno - o2.sno;
            }
        });
        for (Student student : arr)
            System.out.println("student.name = " + student.name + "\tstudent.sno = "+ student.sno);
    }
    
}
class Student implements Comparable<Student>{
    String name;
    int sno;
    public Student(String name, int sno) {
        this.name = name;
        this.sno = sno;
    }
    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.name); // 오름차순 비교
    }
}

 

comparable이 정의된 객체를 정렬 할때는 , Sort() 메소드를 이용한다.

한번정의후에는 변경이 어렵기 때문에, 다른 방법의 정렬을 하기위해서 Comparator를 사용한다.