Comparator 와 Comparable

eunseon·2021년 10월 8일
1

📑 목차

❓Comparator 와 Comparable 정의

✨ 문제에 적용해보기


❓Comparator 와 Comparable 정의 및 차이점

Comparable vs Comparator

  • Comparable: 기본 정렬기준을 세운다. (compareTo override)
  • Comparator: 기본 정렬 기준 외에 다른 기준으로 정렬할 때 사용한다. (compare override)

참고 사항

메소드를 작성할 때에

  • 두 값이 같으면 0
  • 오른쪽 값이 크면 음수입니다.(-1)
  • 왼쪽 값이 크면 양수(+1)를 리턴합니다.

만약,

return o1.y - o2.y;

양수가 리턴되면 왼쪽 인자가 아래로 내려갑니다.

음수가 리턴되면 오른쪽 인자가 아래로 내려갑니다.

✏️ Comparator 와 Comparable를 사용할 수 있는 알고리즘 문제들

11650번: 좌표 정렬하기

11651번: 좌표 정렬하기 2

✨ 문제에 적용해보기

이 중, 좌표 정렬하기 2라는 문제에 Comparator적용해봅시다.

좌표 정렬하기 2라는 문제는

  1. x,y 좌표를 입력받는다.
  2. 입력받은 좌표들을
  • y좌표가 증가하는 순으로 정렬한다.
  • y좌표가 같으면 x가 증가하는 순서로 정렬한다.

이러한 과정으로 문제를 풀었습니다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main_11651_좌표정렬하기2 {
    public static void main(String ... args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        ArrayList<Coordinate> coordinate= new ArrayList<>();

        for(int i= 0; i<N; i++){
            st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            coordinate.add(new Coordinate(x,y));
        }//end of for and Input 

        Collections.sort(coordinate, new Comparator<Coordinate>() {
            @Override
            public int compare(Coordinate o1, Coordinate o2) {
                if(o1.y == o2.y){
                    // 1) y좌표가 같으면 x가 증가하는 순서로 정렬한다.
                    return o1.x - o2.x;
                }else{
                    // 2) y좌표가 증가하는 순으로 정렬한다.
                    return o1.y - o2.y;
                }
            }//end of compare
        });//end of sort

    }//end of main

    public static class Coordinate {
        int x;
        int y;

        public Coordinate(int x, int y){
            this.x = x;
            this.y = y;
        }
    }//end of Coordiate class

}//end of class

Comparable: 기본 정렬기준을 세운다. (compareTo override)
동일한 문제에 Comparable를 적용해봅시다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;

**Comparable:** 기본 정렬기준을 세운다. (compareTo override)

public class Main_11651_좌표정렬하기2_Comparable {
    public static void main(String ... args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        ArrayList<Coordinate> coordinate= new ArrayList<>();

        for(int i= 0; i<N; i++){
            st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            coordinate.add(new Coordinate(x,y));
        }//end of for

       Collections.sort(coordinate);

        for(Coordinate c : coordinate){
            System.out.println(c.x+" "+c.y);
        }
    }//end of main

    public static class Coordinate implements Comparable<Coordinate>  {
        int x;
        int y;

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

        @Override
        public int compareTo(Coordinate c1) {
            if(c1.y == this.y){
                return this.x - c1.x ;
            }else{
                return this.y - c1.y;
            }
        }
    }//end of Coordiate class

}//end of class

사실, 전 IDE를 쓰지 않으면 풀지 못합니다. ㅠㅠ IDE 없이도 풀 수 있도록 해야야겠습니다🙂!

📕 Reference

JAVA : Comparable & Comparator (+ 백준 11650)

[Java] Comparable / Comparator에 대해서 알아보자! (feat. 백준알고리즘-1181)

0개의 댓글