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;
}
}
class Student implements Comparable<Student>{
int no, score;
public Student(int no, int score){
super();
this.no = no;
this.score = score;
}
}
class StudentComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2){
return o1.no - o2.no;
}
}
즉, Comparable이나 Comparator을 사용하려면 인터페이스 내에 선언된 메소드를 반드시 구현해야 한다.
primitive type 같은 경우에는 자바 자체에서 제공되기 때문에 별다른 처리 없이 비교가 가능하지만 새로운 클래스 객체를 만들었다고 생각했을 때 이 객체들을 비교하려면 사용자가 기준을 정해주어야 하기 때문에 Comparable or Comparator가 쓰인다.
Comparable은 자기 자신과 매개변수 객체를 비교
Comparator은 두 매개변수 객체를 비교
Comparable은 자기 자신과 파라미터로 들어오는 객체를 비교하는 것이고, Comparator는 자기 자신의 상태가 어떻던 상관없이 파라미터로 들어오는 두 객체를 비교하는 것이다. 즉, 본질적으로 비교한다는 것 자체는 같지만, 비교 대상이 다르다는 것이다.
이분 글을보자그냥 정리못하겠다
https://st-lab.tistory.com/243