Comparable in Java
안녕하세요, 이번 Posting은 java의 comparable에 대해서 설명하도록 하겠습니다.
Comparable
Comparable을 사용하시는 분들이 많을 것으로 생각되는데, 저 또한 알고리즘을 풀 때 자
사용하고 있습니다. 사용 법은 다음과 같습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Point implements Comparable<Point> {
int x, y;
Point(int x, int y) {
this.x = x; this.y = y;
}
@Override
public int compareTo(Point o) {
if (x > o.x) return 1;
else if (x < o.x) return -1;
else {
if (y > o.y) return 1;
else if (y < o.y) return -1;
else return 0;
}
}
}
Comparable class를 상속 받은 후 compareTo() 메소드를 overriding하여 객체를 비교할 수 있도록 해주는 역할을 하게 되죠. 예를 들어 Arrays.sort()를 사용할 때, 객체간의 비교를 위의 compareTo() 메소드를 사용하여 sorting을 하게 되죠.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Point implements Comparable<Point> { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Point o) { if (x > o.x) return 1; else if (x < o.x) return -1; else { if (y > o.y) return 1; else if (y < o.y) return -1; else return 0; } } } |
저도 항상 헷갈리는 것이 있는데 compareTo() 메소드의 return 값입니다. 객체 자신과 파라미터로 넘어온 객체와 비교를 할 때, 만약 객체 자신이 크다면 양수를 작다면 음수를 같다면 0을 return 시키는 것입니다. 정리 하자면 다음과 같습니다.
> >
1 | this > o(from parameter) ? 1 : (this == o) ? 0 : -1 |