Comparable
정렬 수행 시 기본적으로 적용되는 정렬 기준이 되는 메서드를 정의하는 인터페이스
- package: java.lang.Comparable
- Java에서 제공되는 정렬이 가능한 모든 클래스들이 구현
구현
- implements Comparable<객체 타입>
- public int compareTo(객체 타입 o)
- 오름차순 → 현재 객체 - 파라미터 객체
- 내림차순 → 파라미터 객체 - 현재 객체
사용
- Arrays.sort(___)
- Collections.sort(___)
↓ Arrays.sort() vs Collections.sort()
더보기
Arrays.sort()
- 배열을 정렬할 경우
Collections.sort()
- ArrayList, LinkedList, Vector 등을 정렬할 경우
예시
class Main {
class Point implements Comparable<Point> {
int row, column;
Point(int row, int column) {
this.row = row;
this.column = column;
}
public int compareTo(Point o) {
if(this.row == o.row) return this.column - o.column;
else return this.row - o.column;
}
}
public static void main(String[] args) {
ArrayList<Point> list = new ArrayList<>();
Collections.sort(list);
}
}
Comparator
정렬 가능한 클래스들의 기본 정렬 기준과 다르게 정렬할 때 사용하는 인터페이스
- package: java.util.Comparator
- 내림차순 정렬할 때 많이 사용
구현
- implements Comparator<객체 타입>
- public int compare(객체 타입 o1, 객체 타입 o2)
- 오름차순 → 파라미터 객체1 - 파라미터 객체2
- 내림차순 → 파라미터 객체2 - 파라미터 객체1
사용
- Arrays.sort(___)
- Collections.sort(___)
예시
class Point {
int row, column;
Point(int row, int column) {
this.row = row;
this.column = column;
}
}
class ComparatorImpl implements Comparator<Point> {
public int compare(Point o1, Point o2) {
if(o1.row == o2.row) return o1.column - o2.column;
else return o1.row - o2.column;
}
}
class Main {
public static void main(String[] args) {
ArrayList<Point> list = new ArrayList<>();
ComparatorImpl comparatorImpl = new ComparatorImpl();
}
}
class Main {
class Point {
int row, column;
Point(int row, int column) {
this.row = row;
this.column = column;
}
}
public static void main(String[] args) {
PriorityQueue<Point> pq = new PriorityQueue<>(new Comparator<Point>() {
public int compare(Point o1, Point o2) {
if(o1.row == o2.row) return o1.column - o2.column;
else return o1.row - o2.column;
}
});
}
}
[ 출처 ]
https://gmlwjd9405.github.io/2018/09/06/java-comparable-and-comparator.html
'TIL > Java' 카테고리의 다른 글
[Java] 디자인 패턴 - 싱글톤(Singleton) 패턴 (0) | 2022.06.01 |
---|---|
[Java] BufferedWriter vs StringBuilder (0) | 2022.05.10 |
[Java] 정규표현식 사용하는 방법 (0) | 2022.05.07 |
[Java] 정규표현식 문법 (0) | 2022.05.07 |
[Java] ArrayList를 배열로 변환하는 방법 (0) | 2022.05.04 |