0%

Comparator와Comparable

Comparator와 Comparable

  • 객체 정렬에 필요한 메서드를 정의한 인터페이스
1
Comparable 기본 정렬기준을 구현하는데 사용
2
Comparator 기본 정렬기준 외에 다른 기준으로 정렬하고자할 때 사용
  • compare()compareTo()는 두 객체의 비교결과를 반환하도록 작성. 같으면0, 오른쪽이 크면 음수(-), 작으면 양수(+)
1
publci final class Integer extends Number implements Comparable{
2
  ...
3
  public int compareTo(Integer anotherInteger) {
4
    int v1 = this.value;
5
    int v2 = anotherInteger.value;
6
    
7
    return (v1 < v2 ? -1 : (v1==v2? 0 : 1));
8
  }
9
}

image