import java.util.*;
class Point implements Comparable<Point> {// 포인트라는 클래스 객체를 정렬한다.
public int x, y;
Point(int x, int y){
this.x=x;
this.y=y;
}
@Override
public int compareTo(Point o){
if(this.x==o.x) return this.y-o.y; // x가 같으면 y를 비교
// 오름차순 정렬이므로 this.y-o.y 는 음수
else return this.x-o.x;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Point> arr = new ArrayList<>();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
arr.add(new Point(x, y));
}
Collections.sort(arr); // 정렬의 기준은 compareTo()
for(Point o:arr) System.out.println(o.x+" "+o.y);
}
}
Comparable
Comparable 인터페이스를 상속 받아서 클래스의 기본 정렬 기준을 재정의한다.
this값과 매개변수로 받은 o가 오름차순으로 정렬이 되려면, this - o 가 음수가 되면 된다.
반대로 내림차순으로 정렬이 되게 하려면 o - this 가 음수가 되어야 한다.
즉, 음수 값이 리턴되게 만들면 된다.
Collection.sort(객체)
사용시 대상 객체가 정렬된다. 그 기준은 위에서 Comparable 인터페이스로 정의한 기준에 따라 정렬된다.
'ALGORITHM' 카테고리의 다른 글
[JAVA] 알고리즘 : 정렬- 이분 검색 (0) | 2022.07.28 |
---|---|
[JAVA] 백준 2098번- 상수 (0) | 2022.07.27 |
[JAVA] 알고리즘 : 정렬- 장난꾸러기 (0) | 2022.07.27 |
[JAVA] 백준 1152번- 단어의 개수 (0) | 2022.07.26 |
[JAVA] 알고리즘 : 정렬- 중복 확인 (0) | 2022.07.26 |