JAVA

[java] 정렬하기 (Comparable, Comparator)

kiwiiiv 2021. 9. 9. 16:59

 

이차원 배열에 대한 정렬

 

1) Comparable interface

class Count implements Comparable<Count>{
    //field

    public Count(int id,int weights){
       ..
    }

    //method

    @Override
    public int compareTo(Count c){
        if(this.victories<c.victories){ //이긴 횟수에 대하여 내림차순
            return 1;
        }else if(this.victories==c.victories) {
            if (this.heavier_count < c.heavier_count) { //무거운 선수를 이긴 횟수에 대하여 내림차순
                return 1;
            } else if (this.heavier_count == c.heavier_count) {
                if (this.weights < c.weights) {     //몸무게에 대하여 내림차순
                    return 1;
                } else if (this.weights == c.weights) {
                    if (this.id > c.id) {   //numbering 순으로 "오름차순."
                        return 1;
                    }
                }
            }
        }
        return -1;
    }
}

 

위와 같이 Count라는 객체를 생성 후,

객체 클래스에서 Comparable interface를 implements 하고

compareTo() method를 override하여 정렬 기준을 직접 구현함.

(반환되는 값이 음수 혹은 0일 때에는 객체의 위치가 유지되고, 

양수인 경우에는 두 객체의 위치가 바뀜)

 

위와 같이 구현 후

Arrays.sort()     : Object Array 정렬(int[], Object[])

Collections.sort()     :List Collection 정렬(ArrayList, LinkedList, Vector) 

로 정렬 가능

 

 

 

2)Comparator interface

 

class CountComparator implements Comparator<Count>{

    @Override
    public int compare(Count c1, Count c2) {
        //구현 방식은 동일
    }
}

 

위와 같이 compare method를 Override하여 구현 후 sort 함수를 통하여 정렬.

 

3) Comparator 익명 class

 

 

 

 

 

++

Arrays.sort 구현 예시(익명 클래스? 사용 예)

 

Arrays.sort(Count, (a, b) -> {
            if(a[1] != b[1]) return b[1] - a[1];
            if(a[2] != b[2]) return b[2] - a[2];
            if(a[3] != b[3]) return b[3] - a[3];
            return a[0] - b[0];
        });

 

 


[Java] Comparable와 Comparator의 차이와 사용법 - Heee's Development Blog (gmlwjd9405.github.io)