Java
(Java) Comparable과 Comparator 개념
휘휘o
2020. 12. 16. 11:02
1. Comparable
클래스 선언시 Comparable을 상속받아 기준을 정해 놓을 수 있게해주는 인터페이스 compareTo를 오버라이드 해서 사용한다.
class node implements Comparable<node> {
int x,y;
node(int x, int y){
this.x = x;
this.y = y;
}
@Override
public int compareTo(node o){
if (this.x == o.x){
return this.y - o.y;
}
else {
return this.x - o.x;
}
}
}
위와 같이 사용하며 compareTo를 사용해 정렬 기준을 설정한다.
ArrayList<node> al = new ArrayList<>();
Collections.sort(arrayList);
node 형식을 정의한 정렬순서로 정렬 할 수 있다.
2. Comparator
한 타입에 대해서 정렬을 어떻게 수행할지 정하는 인터페이스
class node {
int x,y;
node(int x, int y){
this.x = x;
this.y = y;
}
}
class comp implements Comparator<node> {
@Override
public int compare(node o1, node o2) {
if (o1.x == o2.x){
return o2.y - o1.y;
}
else {
return o2.x - o1.x;
}
}
}
정렬을 정의할 데이터 형식을 정하고 설정할 수 있다.
ArrayList<node> al = new ArrayList<>();
Collections.sort(al, new comp());
정렬을 수행할 때 정의한 클래스를 생성해 적용시킨다.