Java
[자바] Comparable, Comparator
Sky Titan
2020. 9. 1. 14:25
728x90
Interface Comparable<T>
- 어떤 객체들을 정렬할 때 어떤 기준으로 정렬할지 정할 수 있게 해주는 기능을 제공하는 인터페이스
- 객체들의 기본이 되는 정렬 기준을 정의하는 역할
- 객체들은 Collection.sort() 메서드(혹은 Arrays.sort()) 를 이용해서 정렬을 하게 되는데 이 때 Comparable을 implements한 클래스의 객체라면 클래스 내부에 compareTo() 메서드를 오버라이드해서 미리 정렬 기준을 정해놓을 수 있다.
- Integer, Long, Double 등의 Wrapper 클래스들은 기본적으로 다 Comparable을 구현하고 있다. (기본적으로 오름차순으로 정렬됨)
compareTo(Object o)
- 이 때 Object o는 현재 객체보다 뒤에 있는 객체를 의미
- 양수 값을 return 하게 되면 자리 변경
- 음수 값을 return 하게 되면 자리 유지
예시
ArrayList의 People 객체들을 age를 기준으로 내림차순으로 정렬하는 과정
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
public class Main {
static void solution() throws Exception
{
ArrayList<People> people = new ArrayList<>();
people.add(new People(1));
people.add(new People(2));
Collections.sort(people);
System.out.println(people.get(0).toString());
}
static class People implements Comparable<People>{
int age;
public People(int age)
{
this.age = age;
}
@Override
public String toString() {
return "People{" +
"age=" + age +
'}';
}
@Override
public int compareTo(People o) {
//o 보다 age가 작으면 자리 변경 (내림차순 정렬)
if(age < o.age)
return 1;
else
return -1;
}
}
public static void main(String[] args) {
try
{
solution();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Interface Comparator<T>
- 객체들의 기본 정렬기준과 다른 정렬기준을 적용하고 싶을 때 사용하는 인터페이스
- 클래스 선언단계가 아닌 정렬 메서드를 사용하는 시점에서 적용한다.
- Collections.sort(list, comparator) 와 같은 방식으로 사용됨
compareTo(Object o1, Object o2)
- o1과 o2 객체를 비교한다.
- o2가 리스트에서 뒤에 있는 객체
예시
배열의 People 객체들을 age를 기준으로 내림차순으로 정렬하는 과정
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
public class Main {
static void solution() throws Exception
{
People[] people = new People[2];
people[0] = new People(1);
people[1] = new People(2);
Arrays.sort(people, new Comparator<People>() {
@Override
public int compare(People o1, People o2) {
if(o1.age < o2.age)
return 1;
else
return -1;
}
});
System.out.println(people[0].toString());
}
static class People {
int age;
public People(int age)
{
this.age = age;
}
@Override
public String toString() {
return "People{" +
"age=" + age +
'}';
}
}
public static void main(String[] args) {
try
{
solution();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}728x90