Comparable과 Comparator

Bam·2023년 2월 20일
0

자바

목록 보기
10/19

공통점

객체를 비교할 수 있게 만들어준다.

차이점

Comparable : 자기 자신과 매개변수 객체를 비교한다.
Comparator : 두 매개변수 객체를 비교한다.

Comparable은 인터페이스이다.

class Person implements Comparable{
String name; // 이름
int age; // 나이

public Person(String name, int age){
    this.name = name;
    this.age = age;
}

@Override
public int compareTo(Person o) {
    /*
    비교 구현
    */
}

}
이름과 나이 정보를 담고 있는 Person 클래스이다.
비교 기준이 정해져 있지 않은 Person 객체을 비교할 수 있도록 하기 위해 Comparable을 implements 한 것을 확인할 수 있다.

이때, Comparable 인터페이스의 인자로는 비교할 객체의 타입인 Person을 넘겨준다.

이제 필수 구현 부분인 compareTo(o) 메소드를 정의해야 된다. compareTo(o) 메소드를 살펴보면 파라미터로 하나의 객체만 받는 것을 알 수 있다.
두 객체를 비교하는 메소드인데 파라미터가 하나인 이유는 바로 compareTo(o) 메소드를 호출하는 객체가 하나의 비교 대상이기 때문이다. 즉, 자기자신과 비교하는 것이다.

Person p1 = new Person("Choi", 25);
Person p2 = new Person("Yu", 24);

p1.compareTo(p2);

메소드를 호출한 p1과, 파라미터로 입력된 p2를 비교하는 것이다.

@Override
   public int compareTo(Person o) {
       if(this.age > o.age) {
           return 1;
       }
       else if(this.age == o.age) {
           return 0;
       }
       else { 
 		// this.age < o.age 
           return -1;
       }
   }
Person p1 = new Person("Choi", 25);
Person p2 = new Person("Yu", 24);

p1.compareTo(p2); // 25 > 24 => 1 return 

Comparator


import java.util.Comparator;

class Person implements Comparator<Person> {
    String name; // 이름
    int age; // 나이

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public int compare(Person o1, Person o2) {
        return o1.age - o2.age;
    }
}  
  public class test {
    public static void main(String[] args) throws CloneNotSupportedException{
        Person p1 = new Person("Choi", 25);
        Person p2 = new Person("Yu", 24);
        Person p3 = new Person("Kim", 23);

        p1.compare(p2,p3); // 실행결과 : 1(양수)
    }
}

Comparator 인터페이스는 util 패키지에 있기 때문에 import가 필요하다.

Comparable 인터페이스는 lang 패키지에 있기 때문에
import 필요 X

파라미터로 2개의 객체를 받고, 그 두 객체를 비교한다.

출처 : https://velog.io/@db_jam/Java-Comparable-Comparator-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EA%B0%9D%EC%B2%B4-%EC%A0%95%EB%A0%AC

참고 : https://st-lab.tistory.com/243

profile
Challenger

0개의 댓글