# Comparable 인터페이스가 무엇인가요? 제가 만든 객체들을 자동정렬해야하는데 Comparable 인터페이스를 구현하면 편하다고 합니다. 근데 이게 뭔지 모르겠네요ㅠ
# Comparable 인터페이스란? Comparable 인터페이스는 객체간의 비교를 가능하게 해주는 인터페이스이다. 해당 인터페이스를 구현(implements)한 클래스는 반드시 compareTo(T o) 메소드를 정의해야 한다. ## compareTo 메소드란? 코드를 통해 확인해보자. 아래 코드의 -5가 출력 된다. (~~b를 기준으로 삼았을때 a 는 -5만큼 앞쪽~~) ```java Integer a = new Integer(5); Integer b = new Integer(10); int result = a.compareTo(b); System.out.println(result); ``` 파라메터를 기준으로 삼아 앞쪽에 있으면 음수, 뒤쪽에 있으면 양수값이 나온다. 코드로 바꾸면 이정도가 될 것이다. ```java public int compareTo(Integer target) { return this - target; } ``` 자바에서는 원시형(primitive) 타입의 Wrapper 클래스들은 모두 compareTo() 메소드를 오버라이드있다. 따라서 쉽게 객체간의 비교를 할 수 있다. (compareTo() 메소드가 구현 객체는 Arrays.sort() 메소드를 통해 자동 정렬 가능) ```java int arr = { 5, 4, 8, 1, 3}; Arrays.sort(arr); // 이렇게 쉽게 정렬할 수 있다. ``` ## 사용자 생성 클래스를 쉽게 정렬하려면? Comparable 인터페이스를 구현(implements)하면 Arrays.sort() 메소드를 사용하여 쉽게 정렬할 수 있다. ```java public class Circle { double radius; public Circle(double radius) { this.radius = radius; } } public static void main(String[] args) { Circle c1 = new Circle(5); Circle c2 = new Circle(10); c1.compareTo(c2); } ``` 위와 같은 클래스로 만든 두 객체를 비교하기위해 Comparable 인터페이스를 구현해주자. ```java public class Circle implements Comparable<Circle> { double radius; public Circle(double radius) { this.radius = radius; } @Override public int compareTo(Circle c) { return this.radius - c.radius; } } ``` 구현이 완료되었다면 아래와 같이 해당 객체들은 쉽게 정렬이 가능하다. ```java Circle a = new Circle(5); Circle b = new Circle(1); Circle c = new Circle(3); Circle[] circles = {a, b, c}; Arrays.sort(circles); ```