Programming Language/Java

Java 비교정렬(Comparable vs. Comparator)

수연초이 2021. 6. 8. 12:46

보통 배열 → Arrays.toString(arr)로 출력

linkedList, arrayList, map, set 자료구조의 경우 그냥 print문으로 넣어서 확인 가능

정렬기준을 만들어야하는 경우 무조건 comparable 또는 comparator를 이용해야함

Comparator

정렬 기준이 자주 바뀌는 경우에 사용. 양팔저울 느낌

알고리즘에서는 추천하지 않음

'new Comparator<객체>' 로 비교 기준 생성

 

기본(Int)형 비교:

Collections.sort(students, new Comparator(<Student>(){
	@Override
    public int compare(Studnet o1, Studnet 02){
    	return o1.score - o2.score;
	}
};

오름차순 -> 첫번째를 기준

내림 차순 -> 두번째를 먼저 쓰기 (o2.score - o1.score);

 

double형 비교(실수 비교):

Collections.sort(students, new Comparator(<Student>(){
	@Override
    public int compare(Studnet o1, Studnet 02){
    	if (o1.score > o2.score)
        	return 1;
        else if(o1.score < o2.score)
        	return -1;
        else
        	return 0;
	}
};

compare함수의 리턴타입이 Int형이라서 단순히 뺄셈 연산으로 리턴 X.

소수점이 나올 수 있으므로 comparator의 정석적인 방법(리턴 -1, 1, 0)으로 구현

 

String 비교(람다식 사용ver.)

Collections.sort(students, (o1, o2) -> {	
	return o1.name.compareTo(o2.name);
});

compareTo에서 String비교 가능함을 이용

Comparable

항상 일정한 기준으로 정렬.

알고리즘 문제 풀 때 추천

객체 자체를 비교가능하게 만들어서 정렬

예제:

ArrayList<Product> foods = new ArrayList<>();

class Product implements Comparable<Product>{
	String name;
    String maker;
    int price;
    
    public Product(String name, String maker, int price){
    	//생성자
    }
    
    // Product 내부에서 비교할수 있는 함수 구현 
    @Override
    public int compareTo(Product o) {
    	return this.price - o.price;
    }
}

위처럼 객체가 Comparable을 implements 하여 compareTo함수를 구현

Collections.sort(foods);

이렇게 .sort로 정렬 실행

 

정렬 기준 2개:

class Product implements Comparable<Product>{
	
    // ...
    
    @Override
    public int compareTo(Product o) {
    	//가격이 같은 경우 이름으로 정렬 
    	if(this.price - o.price){
        	return this.name.compareTo(o.name);
        }
    	return this.price - o.price;
    }
}