티스토리 뷰

[JAVA]/JAVA

[JAVA] Comparable & Comparator

춘햄 2021. 3. 25. 17:06

1. Comparable과 Comparator?

 1) Comparable 인터페이스

    - java.lang.compable 패키지에 있는 인터페이스

    - 정렬 수행시 기본적으로 적용되는 정렬 기준을 정하는 메소드를 정의해놓는 인터페이스이다.

 2) Comparator 클래스

    - java.util.Comparator 패키지에 있는 클래스

    - 기본 정렬 기준과 다른 기준을 정하여 정렬을 할 필요가 있을 때 사용

 

2. 사용 방법

 1) Comparable

 

기본적인 Comparable 인터페이스의 사용 방법은 다음 코드와 같이 Comparable을 정렬이 필요한 클래스을 제네릭 타입으로 implements해주고, compareTo 메소드를 오버라이딩하여 정렬 기준을 스스로 정해주면 된다.

 

Code:

public class Student implements Comparable<Student>{
		private String name; 
		private int id; 
		private double score;

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

		public String toString() { 
			return "이름: " + name + ", 학번: " + id + ", 학점: " + score;
		}
		
		@Override
		public int compareTo(Student anotherStudent) { 
			return Integer.compare(id, anotherStudent.id);
		}
}

여기서 compareTo 메소드로 반환되는 Integer.compare의 기본 구조는 다음과 같다.

 

Code:

public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }

즉, Integer.compare을 사용하지 않고, 직접 다른 기준을 정해줘도 상관 없다. 기본적으로 위의 Student클래스에 정의된 구조가 오름차순 정렬이며, 내림차순 정렬은 compare에 들어간 인자의 순서를 반대로 하면 된다.

 

Arrays.sort()와 같은 기본 정렬 메서드를 사용할 때는 반드시 정렬할 객체 내에 comparable 인터페이스가 구현이 되어 있는 지 확인해야한다.

 

Main Class Code:

import java.util.Arrays;

public class Main {

	public static void main(String[] args) {
		Student student[] = new Student[5];
		student[0] = new Student("Dave", 20120001, 4.2);
		student[1] = new Student("Amie", 20150001, 4.5);
		student[2] = new Student("Emma", 20110001, 3.5);
		student[3] = new Student("Brad", 20130001, 2.8);
		student[4] = new Student("Cara", 20140001, 4.2);
		
		Arrays.sort(student); //퀵소트
		for(int i=0;i<5;i++) //toString에 정의된 형식으로 출력
			System.out.println(student[i]);
	}

}

Output:

 

이름: Emma, 학번: 20110001, 학점: 3.5
이름: Dave, 학번: 20120001, 학점: 4.2
이름: Brad, 학번: 20130001, 학점: 2.8
이름: Cara, 학번: 20140001, 학점: 4.2
이름: Amie, 학번: 20150001, 학점: 4.5

 

 2) Comparator

 

지정해놓은 Student클래스의 정렬 기준은 학번 오름차순이다.  하지만 이 기본 정렬 기준 말고 다른 항목을 기준으로 우선 정렬을 하고 싶을 때 Comparator 클래스를 사용한다.

성적을 기준으로 내림차순 정렬을 우선적으로 하고, 성적이 같으면 학번으로 오름차순 정렬한다고 가정하면, 우선 Student 클래스의 코드는 추가할 것이 없다.

그러나 새로운 정렬 기준을 적용하기 위해 sort매소드에서 직접 Comparator 객체를 선언하여 내부에서 compare 매소드를 구현하여 기준을 정해줘야한다.  

sort를 직접 사용한 Main 클래스의 코드를 보자

 

Code:

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

public class Main {

	public static void main(String[] args) {
		Student student[] = new Student[5];
		student[0] = new Student("Dave", 20120001, 4.2);
		student[1] = new Student("Amie", 20150001, 4.5);
		student[2] = new Student("Emma", 20110001, 3.5);
		student[3] = new Student("Brad", 20130001, 2.8);
		student[4] = new Student("Cara", 20140001, 4.2);
		
		Arrays.sort(student, new Comparator<Student>(){
			public int compare(Student s1, Student s2) {
				double s1Score = s1.score;
				double s2Score = s2.score;
				if(s1Score == s2Score){ 
					return Double.compare(s1.id, s2.id); 
				}
				return Double.compare(s2Score, s1Score);
			}
		});
		for(int i=0;i<5;i++)
			System.out.println(student[i]);
	}

}

Output:

 

이름: Amie, 학번: 20150001, 학점: 4.5
이름: Dave, 학번: 20120001, 학점: 4.2
이름: Cara, 학번: 20140001, 학점: 4.2
이름: Emma, 학번: 20110001, 학점: 3.5
이름: Brad, 학번: 20130001, 학점: 2.8

Comments