[Java] Comparator Interface

2019. 11. 24. 15:06

Comparator interface를 implements  후 compare()메소드를 오버라이드한다

 

compare() 메소드

첫번째 파라미터 < 두번째 파라미터 = 음수 리턴

첫번째 파라미터 == 두번째 파라미터 = 0리턴

첫번째 파라미터 > 두번째 파라미터 : 양수 리턴

=> 음수 또는 0이 리턴되면 객체의 자리가 그대로 유지, 양수인 경우에 두 객체의 자리가 변경

Integer.compare(x,y)와 동일한 개념

(return (x<y)? -1 : ((x==y) ? 0 : 1);

* 내림차순 정렬은 두 파라미터의 위치를 바꿔줌

Integer.compare(y,x)

 

주로 사용했던 곳은 2차원 배열에서 한가지 배열 요소에따라 정렬할때 사용

 

예시)

Arrays.sort(arr, new Comparator<int []>() {
            public int compare(int a[], int b[]) {
                if(a[0]==b[0]) return Integer.compare(a[1], b[1]);
                else return Integer.compare(a[0],b[0]);
            }
        });
 Arrays.sort(arr, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return (o1[0] < o2[0] ? -1 :((o1[0] == o2[0]) ? 0 :1);
            }
        });

* Arrays.sort(T[] Collections.reverseOrder()) //내림차순 정렬, 배열은 primitive data type이 아니라 객체의 배열을 사용

* 간단하게 일반적인  primitive data type 의 배열을 오름차순 정렬하고 싶을때는

public static void sort(int[] a)

Sorts the specified array into ascending numerical order.

 

* 혹은 내림차순이나 개인나름대로 정렬을 하고싶을 경우에는 (원시 자료형은 사용불가하고 객체 배열을 사용한다)

public static <T> void sort(T[] a, Comparator<? super T> c)

Sorts the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

 

ref)

https://gmlwjd9405.github.io/2018/09/06/java-comparable-and-comparator.html

 

[Java] Comparable와 Comparator의 차이와 사용법 - Heee's Development Blog

Step by step goes a long way.

gmlwjd9405.github.io

https://emflant.tistory.com/210

 

자바에서 배열 정렬하기

자바에서 배열 및 리스트를 오름차순 혹은 내림차순으로 정렬하려 한다면, 알맞은 소트 알고리즘을 이용해서 개인적으로 모듈화하여 계속 사용하면 제일 좋다. 하지만 배열의 크기가 그닥 크지도 않고, 굳이 고성..

emflant.tistory.com

 

+ Recent posts