
ref : https://st-lab.tistory.com/243
객체를비교할 수 있도록 만들기 위한인터페이스compareTo(T o)메소드 하나가 선언되어 있는인터페이스자기 자신과,매개변수로 들어오는 객체를비교- int 값을 반환
- 양수 :
비교 기준이더 큰 경우- 0 : 자신과
같은 경우- 음수 :
비교 기준이더 작은 경우
- 기본적으로
반환값을양수/0/음수로 나누어서조건문을 할수도 있지만두 값의 차이를 통해3개 비교문을생략해서 사용 (효율적)class Student implements Comparable<Student> { int age; // 나이 int classNumber; // 학급 Student(int age, int classNumber) { this.age = age; this.classNumber = classNumber; } @Override public int compareTo(Student o) { /* * 만약 자신의 age가 o의 age보다 크다면 양수가 반환 될 것이고, * 같다면 0을, 작다면 음수를 반환할 것이다. */ return this.age - o.age; } }
객체를비교할 수 있도록 만들기 위한인터페이스compare(T o1, T o2)메소드 하나가 선언되어 있는인터페이스- 자기 자신이 아닌,
매개변수로 들어오는 객체o1,o2를비교
(Comparable의compareTo()는자신이 대상이었음 즉,비교대상이 다름)
객체 내부에 구현
객체 내부에구현이 가능하지만,익명 객체 방법이 더효율적import java.util.Comparator; // import 필요 class Student implements Comparator<Student> { int age; // 나이 int classNumber; // 학급 Student(int age, int classNumber) { this.age = age; this.classNumber = classNumber; } @Override public int compare(Student o1, Student o2) { /* * 만약 o1의 classNumber가 o2의 classNumber보다 크다면 양수가 반환 될 것이고, * 같다면 0을, 작다면 음수를 반환할 것이다. */ return o1.classNumber - o2.classNumber; } }
익명 객체 사용 --> 권장
- 객체 자신과 상관 없이
매개변수로 받는 객체 2개를비교하기 때문에사용에 불편함을 가짐
- 보통 아래처럼
익명 객체(클래스)를생성해서 사용한다익명 객체를main 내부에 지역변수로 만들거나 /main 밖에서 static으로 선언후 사용 가능import java.util.Comparator; public class Test { public static void main(String[] args) { // 익명 객체 구현방법 1 Comparator<Student> comp1 = new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.classNumber - o2.classNumber; } }; } // 익명 객체 구현 2 public static Comparator<Student> comp2 = new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.classNumber - o2.classNumber; } }; } // 외부에서 익명 객체로 Comparator가 생성되기 때문에 클래스에서 Comparator을 구현 할 필요가 없어진다. class Student { int age; // 나이 int classNumber; // 학급 Student(int age, int classNumber) { this.age = age; this.classNumber = classNumber; } }
원형
주 사용 API
Arrays.sort()Collections.sort()
Collection정렬List/ArrayList등- 기본적으로
오름차순이며,내림차순을 원할 경우직접 정의하거나Collections.reverseOrder() 사용- 등
특징
- 기본적으로
오름차순 정렬참조 타입을정렬할 때에는Comparable/Comparator와 함께 정렬 수행
compareTo()/Comparator반환 결과에 따른 정렬
음수or0:교환 X양수:교환 O
- 내림차순 정렬 방법(
참조 타입)
Comparable/Comparator에서반환값의 부호를 바꿔줘야 함미리 정의된 Comparator사용 -->Collections.reverseOrder()
:Arrays.sort(arr, Collections.reverserOrder())
- Arrays.sort(
객체 배열)import java.util.Arrays; public class Test { public static void main(String[] args) { MyInteger[] arr = new MyInteger[10]; // 객체 배열 초기화 (랜덤 값으로) for(int i = 0; i < 10; i++) { arr[i] = new MyInteger((int)(Math.random() * 100)); } // 정렬 이전 System.out.print("정렬 전 : "); for(int i = 0; i < 10; i++) { System.out.print(arr[i].value + " "); } System.out.println(); Arrays.sort(arr); // 정렬 이후 System.out.print("정렬 후 : "); for(int i = 0; i < 10; i++) { System.out.print(arr[i].value + " "); } System.out.println(); } } class MyInteger implements Comparable<MyInteger> { int value; public MyInteger(int value) { this.value = value; } @Override public int compareTo(MyInteger o) { return this.value - o.value; } }
- Arrays.sort(
객체 배열,정렬 기준)정렬 기준으로는비교를 위한 익명 객체를삽입하면 됨import java.util.Arrays; import java.util.Comparator; public class Test { public static void main(String[] args) { MyInteger[] arr = new MyInteger[10]; // 객체 배열 초기화 (랜덤 값으로) for(int i = 0; i < 10; i++) { arr[i] = new MyInteger((int)(Math.random() * 100)); } // 정렬 이전 System.out.print("정렬 전 : "); for(int i = 0; i < 10; i++) { System.out.print(arr[i].value + " "); } System.out.println(); // MyInteger에 대한 Comparator을 구현한 익명객체를 넘겨줌 Arrays.sort(arr, comp); // 정렬 이후 System.out.print("정렬 후 : "); for(int i = 0; i < 10; i++) { System.out.print(arr[i].value + " "); } System.out.println(); } static Comparator<MyInteger> comp = new Comparator<MyInteger>() { @Override public int compare(MyInteger o1, MyInteger o2) { return o1.value - o2.value; } }; } class MyInteger { int value; public MyInteger(int value) { this.value = value; } }
Comparable/Comparator는 모두객체를 비교하기 위한 기능의인터페이스
- 두 인터페이스는
비교하는 대상이다르다
- Comparable :
호출한 자신과매개변수 객체의 비교- Comparator :
매개변수 객체 2개 간비교
- 정렬(
sort)와 함께 사용 될 때
- Comparable :
오름차순 정렬만할 때 주로 사용- Comparator :
내림차순이나특별한 기준에 따라비교할 때 주로 사용