기본형 데이터의 경우 간단하게 Arrays.sort() 와 같은 메서드로 정렬이 가능하다.
하지만 특정 객체의 경우 기본형 타입과는 다르게 정렬 기준을 정의해야 하는 경우가 있다. 이때 Java의 Comparable을 이용할 수 있다.
Java의 Comparable은 interface이기 때문에 이를 상속받는 class에서는 Comparable interface에 있는 compareTo를 구현해야한다.
위 사진에서 보이듯 compareTo는 비교 결과에 따라 int를 반환한다.
- 들어온 객체가 자신보다 크면: 음수 리턴
- 들어온 객체와 자신이 같으면: 0 리턴
- 들어온 객체보다 자신이 크면: 양수 리턴
이를 이용하여 x, y 좌표를 입력 받고 x 기준으로 오름차순으로 정렬하고 x가 같다면 y 기준으로 오름차순으로 정렬하는 코드는 다음과 같다.
class Point implements Comparable<Point> {
public int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(@NotNull Point o) {
if (this.x == o.x) {
return this.y - o.y;
} else {
return this.x - o.x;
}
}
}
public class Main {
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Point> input = new ArrayList<>();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
input.add(new Point(x, y));
}
Collections.sort(input);
for (Point point : input) {
System.out.println(point.x + " " + point.y);
}
}
}
결과
내림차순이든 오름차순이든 compareTo 함수에서 음수가 리턴되도록 하면 된다.
- 오른차순의 경우: this - o
- 내림차순의 경우: o - this