본문 바로가기

old/Programming

Java에서 컴페레터comparator와 컴페터블compatable의 차이점

반응형

정의

컴페레터comparator와 컴페터블compatable은 둘다 인터페이스interfaces이며, 어레이array나 리스트list를 여러 특수한 조건에 맞춰서 정렬을 시키기 위해 만들어져 있다.

목표

컴페레터comparator와 컴페터블compatable은 서로 매우 비슷하며, 햇갈리기가 쉽다. 차이점을 알아보고 어떤걸 쓰는게 좋은지 알아보자.

차이점

Comparable Comparator
java.lang package. java.util package.
클래스에 영향을 줌 클래스에 영향을 주지 않음
compareTo() 메서드를 오버라이드하며, 1개의 파라미터를 가짐 compare() 메서드를 생성하며, 2개의 파라미터를 가짐
Collections.sort(List)로 사용 Collections.sort(List, Comparator)로 사용
Arrays.sort(array)로 사용 Arrays.sort(array, myComparator)로 사용

결론

되도록이면 comparator를 사용해서 여러 조건을 가진 정렬을 만드는게 바랍직하다.

여러명이서 팀웍을 할때, 어떤 클래스의 정렬이 무조건적으로 어떤조건에 맞춰서 정렬되어야 한다면, compatable를 써도 괜찮다. 하지만 이런 경우가 아닐경우 대부분은 comparator를 사용하는게 팀웍에도 좋고 햇갈리지 않는다.

예제

custom class with compatable


import java.lang.Comparable;

public class customPoint implements Comparable<customPoint> {

    private int x = 0;
    private int y = 0;

    public customPoint(int x, int y) {
        this.x = x;
        this.y = y;

    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public int compareTo(customPoint p2) { //이와 같은 여러 조건이 가능하다
        if (this.x > p2.x) {
            return 1; // x 에 따라서 오름차순으로 정렬
        } else if (this.x == p2.x) {
            if (this.y < p2.y) { // x로 정렬된다음 y는 내림자순으로 정렬
                return 1;
            }
        }
        return -1;
    }
}

comparator


import java.awt.*;
import java.util.Comparator;

public class MyComparator  implements Comparator<Point> {

    public int compare(Point p1, Point p2) {
        if (p1.x > p2.x) {
            return 1; //  x 에 따라서 오름차순으로 정렬
        } else if (p1.x == p2.x) {
            if (p1.y < p2.y) { // x로 정렬된다음 y는 내림자순으로 정렬
                return 1;
            }
        }
        return -1;
    }
}

main


import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        java.util.List<Point> pointList = new ArrayList<Point>();
        pointList.add(new Point(10, 10));
        pointList.add(new Point(1, 8));
        pointList.add(new Point(5, 2));
        pointList.add(new Point(1, 2));
        pointList.add(new Point(5, 5));
        pointList.add(new Point(10, 1));

        System.out.println("current list");
        for (Point temp : pointList) {
            System.out.println("x: " + temp.x + "  " + "y: " + temp.y);
        }
        System.out.println("Comparator sorted list");
        MyComparator myComparator = new MyComparator();
        Collections.sort(pointList, myComparator);
        for (Point temp : pointList) {
            System.out.println("x: " + temp.x + "  " + "y: " + temp.y);
        }
        System.out.println("===========================================================");

        List<customPoint> pointList2 = new ArrayList<>();
        pointList2.add(new customPoint(10, 10));
        pointList2.add(new customPoint(1, 8));
        pointList2.add(new customPoint(5, 2));
        pointList2.add(new customPoint(1, 2));
        pointList2.add(new customPoint(5, 5));
        pointList2.add(new customPoint(10, 1));

        System.out.println("current list");
        for (customPoint temp : pointList2) {
            System.out.println("x: " + temp.getX() + "  " + "y: " + temp.getY());
        }

        System.out.println("Comparable sorted list");
        Collections.sort(pointList2);
        for (customPoint temp : pointList2) {
            System.out.println("x: " + temp.getX() + "  " + "y: " + temp.getY());
        }

    }
}

결과값


current list
x: 10  y: 10
x: 1  y: 8
x: 5  y: 2
x: 1  y: 2
x: 5  y: 5
x: 10  y: 1
Comparator sorted list
x: 1  y: 8
x: 1  y: 2
x: 5  y: 5
x: 5  y: 2
x: 10  y: 10
x: 10  y: 1
===========================================================
current list
x: 10  y: 10
x: 1  y: 8
x: 5  y: 2
x: 1  y: 2
x: 5  y: 5
x: 10  y: 1
Comparable sorted list
x: 1  y: 8
x: 1  y: 2
x: 5  y: 5
x: 5  y: 2
x: 10  y: 10
x: 10  y: 1
반응형