Comparater, Comparable

서현서현·2023년 8월 6일
0

JAVA

목록 보기
25/27

두개 모두 인터페이스다.
Comparable 인터페이스는 compareTo(T o) 메소드를 재정의 해야하고
Comparator 인터페이스는 compare(T o1,o2)메소드를 재정의 해야한다.

자 이제 예시를 들어보자. 나는 학생들의 정보를 가진 Class를 정렬하려고 한다. 이때 문제가 생긴다. 무엇을 기준으로 정렬할것인가?
나이순일수도, 이름순일수도, 학번순일수도 있다.

이 문제를 해결하기 위해 Comparator와 Comparable을 사용한다.
그렇다면 두 인터페이스는 어떤 역할차이가 있을까?

Comparable은 "자기자신과 매개변수 객체를 비교"하는것
Comparator는 "두 매개변수 객체를 비교"하는것 에서 차이가있다.

Comparable

public class Student implements Comparable<Student> {
	int age, classNumber;
    String name;
    
	@Override
    public int compareTo(Student o){
    	return this.age - o.age;
    }
}

Comparator

public class Student implements Comparator<Student> {
	int age, classNumber;
    String name;
    
	@Override
    public int compare(Student o1, Student o2){
    	return o1.age - o2.age;
    }
}

익명객체로 Comparator 구현

(CF) Comparable도 익명객체로 구현 할 수 있긴하나 그럴 필요도 없고 복잡해지기만 함. 원래 생긴게 매개변수 하나만 받으니까요...

public class Test {
	public static void main(String[] args) {
    
    	//구현법 1
    	Comparator<Student> comp1 = new Comparator<Student>() {
        	@Override
            public int compare(Student o1, Student o2){
            	return o1.age = o2.age;
            }
        }
    }
    
	//구현법2
	public static Comparator<Student> comp2 = new Comparator<Student>() {
		@Override
		public int compare(Student o1, Student o2){
			return o1.age - o2.age;
		}
	}
}

정렬

자바에서 정렬은 특별한 정의가 없는 한 '오름차순' 정렬된다.
즉, 선행원소가 후행원소보다 작다는것을 의미한다. 따라서 compare나 compareTo를 사용할때 음수가 나오면 두 원소의 위치를 바꾸지 않는다

따라서 Compareable을 구현한 후, Arrays.sort()하면 정렬이 된다.

Comparator로도 가능하다. 이땐 익명객체를 생성해서 구현해보겠다

static Comparator<Student> comp = new Comparator<Student>() {
	@Override
    public int comapare(Student o1, Student o2){
    	return o1.value - o2.value;
    }
}

public static void main(String[] args) {
	Arrays.sort(arr, comp); //Student에 대한 Comparator를 구현한 익명객체를 넘겨준다
}

내림차순 하고싶으면 선행, 후행원소를 뒤바꿔주면 된다!

0개의 댓글