ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] Comparable과 Comparator
    Java 2016. 10. 28. 20:04

    Comparable, Comparator - 정렬을 하기위한 인터페이스


    두가지의 차이는 무엇일까 ?


    공통점 - 두 인터페이스 모두 public으로 선언, 모든 용도의 자료를 담을 수 있다.


    Comparable 인터페이스 - 자연스러운 순서로 정렬

    Comparator 인터페이스 - 원하는 대로 정렬 순서를 지정


    Customer클래스를 정의


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public class Customer {
        private int id;
        private String name;
        private String phoneNum;
        
        public Customer(int id, String name, String phone) {
            this.id = id;
            this.name = name;
            this.phoneNum = phone;
        }
    }
    cs

    Customer가 여러명있고 이를 정렬하기 위해서 Collections.sort(); 실행한다.



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    ArrayList<Customer> al = new ArrayList<Customer>();
            
            al.add(new Customer(3"가나다""01020202020"));
            al.add(new Customer(10"너나다""01032102020"));
            al.add(new Customer(13"다나다""01043202020"));
            al.add(new Customer(4"라나다""01023202020"));
            
            Collections.sort(al);
            for(Customer c: al) {
                System.out.println(c.id);
            }

    cs



    실행결과 어느 속성을 참고하여 정렬을 해야할지 정의하지 않았기 때문에 에러가 발생하였다.
    의도했던 바와 같이 정렬이 되게 하려면 Comparable 인터페이스를 구현해야한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public class Customer implements Comparable<Customer> {
        private int id;
        private String name;
        private String phoneNum;
        
        public Customer(int id, String name, String phone) {
            this.id = id;
            this.name = name;
            this.phoneNum = phone;
        }
     
        @Override
        public int compareTo(Customer o) {
            // TODO Auto-generated method stub
            int compareNum = ((Customer)o).id;
            return this.id - compareNum;
        }
        
    }
    cs



    Comparable 인터페이스를 구현하고 compareTo() 메소드를 오버라이딩 하였으므로, Array는 이 정보를 이용하여 정렬이 된다.


    만약 id가 아닌 name을 가지고 정렬을 해야한다면 compareTo 메소드를 다시 정의해야 할까?

    이런 경우에 Comparator 인터페이스를 사용한다.


    1
    2
    3
    4
    5
    6
    7
    8
    public class CustomerComparator implements Comparator<Customer> {
     
        @Override
        public int compare(Customer o1, Customer o2) {
            return o1.name.compareTo(o2.name)*-1;
        }
     
    }
    cs



    'Java' 카테고리의 다른 글

    [Java] 이진탐색 Binary Search  (0) 2016.11.04
    [Java] 합병정렬 Merge Sort  (1) 2016.11.03
    [Java] 퀵 정렬 Quick Sort  (0) 2016.11.02
    [Java] 삽입정렬 Insertion Sort  (0) 2016.10.29
    [Java] 버블정렬 Bubble Sort  (0) 2016.10.29
Designed by Tistory.