Comparable vs Comparator
참고 사항
메소드를 작성할 때에
만약,
return o1.y - o2.y;
양수가 리턴되면 왼쪽 인자가 아래로 내려갑니다.
음수가 리턴되면 오른쪽 인자가 아래로 내려갑니다.
이 중, 좌표 정렬하기 2라는 문제에 Comparator를 적용해봅시다.
좌표 정렬하기 2라는 문제는
이러한 과정으로 문제를 풀었습니다.
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 없이도 풀 수 있도록 해야야겠습니다🙂!
JAVA : Comparable & Comparator (+ 백준 11650)
[Java] Comparable / Comparator에 대해서 알아보자! (feat. 백준알고리즘-1181)