java.lang.Comparable< T>
int compareTo(T other)
자신과 인자로 전달받는 타 원소와 비교하여 정수를 리턴한다.
음수 결과: 타 원소가 크다.
0 결과 : 두 원소가 같다.
양수 결과 : 자신이 크다.
// 학생들의 학번순으로 정렬
class Student implements Comparable<Student>{
int no, score;
public Student(int no, int score){
super();
this.no = no;
this.score = score;
}
@override
public int compareTo(Student o){
return this.no - o.no;
}
}
java.util.Comparator< T>
int compare(T o1, T o2)
비교 대상의 두 원소가 아닌 별도의 도우미 역할
두 원소(o1,o2)를 비교하여 정수를 리턴한다.
- 음수결과 : o2원소가 크다.
- 0 결과 : 두 원소가 같다.
- 양수 결과 : o1 원소가 크다.
// Student 클래스는 위와 동일
class StudentComparator implements Comparator<Student>{
@override
public int compare(Student o1, Student o2){
return o1.no - o2.no;
}
Arrays.sort()는 비교판단을 하는 메소드가 아니다.