Beny's Study
12. Comparator와 Comparable 본문
Comparator & Comparable
객체를 정렬하는데 필요한 메서드를 정의한 인터페이스(정렬 기준을 제공함)
Comparator : 기본 정렬기준을 구현하는데 사용(default)
Comparable : 기본 정렬기준 외에 다른 기준으로 정렬하고자 할때 사용
public interface Comparator{
int compare(Object o1, Object o2);//o1,o2비교
boolean equals(Object obj);
}
public interface Comparable{
public int comparaTo(Object o);//객체(o)를 자신과 비교
}
compare(), compareTo()
두개 객체의 비교 결과를 반환하도록 구현해야 함.
비교하는 두 객체가 같으면 0, 왼쪽이 크면 양수, 왼쪽이 작으면 음수
public final class Integer extends Number implements Comparable{
...
public int comparaTo(Object o){
reutrn comparaTo((Integer)o);
}
public int comparaTo(Integer anotherInteger){
int thisVal = this.value;
int anotherVal=anotherInteger.value;
//비교하는 값이 크면-1, 같으면0, 작으면1을 반환.
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0:1));
}
...
}
"본 인터넷 사이트 내의 모든 이미지, 문구, 콘텐츠, 내용 등에 대한 저작권은 76beny에게 있습니다.
이를 무단으로 도용, 복사, 전재, 재배포, 2차 변형 등을 할 경우
민, 형사상 법적 조치 등 저작권법에 의거하여 처벌 받을 수 있습니다."
'[JAVA] > 13. 제네릭과 컬렉션' 카테고리의 다른 글
14. TreeSet & 이진탐색트리 (0) | 2022.05.01 |
---|---|
13. HashSet (0) | 2022.05.01 |
11. Arrays (0) | 2022.04.30 |
10. Iterator, ListIterator, Enumeration (0) | 2022.04.30 |
09. Stack과 Queue (0) | 2022.04.30 |