(수근수근)

Comparator & Comparable 본문

JAVA

Comparator & Comparable

InformationFarm 2020. 8. 31. 11:47

코딩테스트 할 때 기준에 맞춰서 정렬을 할 일이 정말 많다.

근데 맨날 개념 모르고 그때 그때  찾아서 코드 복붙만 했었다... 

Collections.sort() 만 사용하던지........ 

 

 

1. Comparator  Comparable은 인터페이스이다

실제 소스를 확인해보면 아래와 같이 작성되어 있다.

public interface Comparator{
	int compare(Object o1, Object o2);
    boolean equals(Object obj);
}


public interface Comparable{
	int compareTo(Object o);
}

 

둘이 다른 함수 이름 compare / compareTo로 되어있지만 이름만 다를 뿐 비교한다는 기능은 똑같다!

비교상대와 같으면  0, 작으면 -1 ,더 크면 1 값을 반환한다.

 

그렇다면 왜 같은 기능을 하는 것을 2개로 나누었을까?

결론적으로 말하자면

Comparable 은 기본 정렬기준(오름차순)을 구현하는데 사용하고

Comparator 는 기본 정렬기준 외에 다른기준으로 정렬하고자 할 때 사용한다.

 

내가 코딩테스트 할 때... 항상 Comparator만 만들며...

왜 Comparable로는 안하지하며 공부를 안하려고 했던 내가 참...ㅋㅋㅋ

 

2. 우리가 사용하는 대부분의 정렬 API 안에는 Comparator와 Comparable을 사용하고 있다.

우리가 당연하게 사용해온 많은 JDK의 정렬시 사용하는 함수들은 실제로 내부 소스를 까보면 

Comparator와 Comparable로 구현이 많이 되어있다.

 

-우리가 TreeSet에 Integer를 저장할 때 자동으로 정렬되는 것

- Colllections.sort()

- Collections.reverse()

 

등의 다양한 함수들은 실제로 Comparator와 Comparable을 구현하고 있는 것이라고 보면 된다!

 

3. 예제

public class sortTest {
	public static void main(String[] args) {
		 ArrayList<Student> studentArr =  new ArrayList<>();
		    int[] score = {10,20,30,20,10,4,2};
		    String[] names = {"청수","영희","민하","주하","민주","스팟","코나"};

		    for(int i=0;i<7;i++){
		        studentArr.add(new Student(score[i],names[i]));
		    }
		    //정렬 score가 높은 순서대로
		    Comparator<Student> comparator =  new Comparator<Student>() {
		        @Override
		        public int compare(Student o1, Student o2) {
		            return o2.getMathScore() - o1.getMathScore();
		        }
		    };

		    Collections.sort(studentArr, comparator);
		    for(Student i : studentArr) {
			    System.out.println(i.getMathScore());
		    }
	}
}

class Student {
    int mathScore;
    String name;

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

    public int getMathScore() {
        return mathScore;
    }

    public void setMathScore(int mathScore) {
        this.mathScore = mathScore;
    }
}

 

Comments