목차
Comparable
Comparable 인터페이스는 compareTo(T o) 메소드가 하나 선언되어 있다.
이 말은 Comparable 인터페이스를 사용하려면 compareTo(T o)을 재정의해야 한다는 것이다.
자기 자신과 매개변수 객체를 비교 한다.
class dotone implements Comparable<dotone> {
int one;
int two;
dotone(int one, int two) {
this.one = one;
this.two = two;
}
// 정수 비교
public int compareTo(dotone o) {
return this.two - o.two;
}
}
class dottwo implements Comparable<dottwo> {
String one;
String two;
dottwo(String one, String two) {
this.one = one;
this.two = two;
}
// String 비교
public int compareTo(dottwo o) {
return this.two.compareTo(o.two);
}
}
Comparator
Comparator 인터페이스는 compare(T o1, T o2) 메소드를 구현하면 된다.
두 매개변수의 객체를 비교한다.
Comparable와 Comparator는 비교하는 역할을 같지만, 비교 대상이 다르다.
Comparable은 lang 패키지에 있어 import를 해줄 필요가 없지만, Comparator는 util 패키지 안에 있으므로 import를 해줘야 합니다.
[이후 작성]