Comparable<T> 인터페이스

2024. 6. 6. 00:30·algorithm

 

Comparable : 객체의 자연 순서를 정의하는데 사용된다.

 - 구현 시 객체를 정렬할 수 있는 방법을 제공한다.

 - 하나의 메서드 compareTo를 선언

 

Comparable 인터페이스 구현

 - 클래스 선언시 'Comparable<T>' 인터페이스를 구현한다. 여기서 T는 클래스의 타입.

 - 'compareTo' 메서드를 오버라이드하여 두 객체를 비교하는 로직을 작성한다.

 

compareTo 메서드의 반환값

 - 음수 : 현재 객체가 비교 객체보다 작음

 - 양수 : 현재 객체가 비교 객체보다 큼

 - 0 : 두 객체가 같음

 

예제

public class Person implements Comparable<Person> {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int compareTo(Person other) {
        // 나이를 기준으로 비교
        return Integer.compare(this.age, other.age); //밑에 따로 설명
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        Collections.sort(people);

        for (Person person : people) {
            System.out.println(person);
        }
    }
}

 

Collections.sort()

 - comparable 인터페이스를 구현한 객체들의 리스트를 정렬

 - 'List<String>', 'List<Integer>' 또는 'Comparable' 인터페이스를 구현한 사용자 정의 객체 리스트를 정렬할 수 있다.

 - List 타입들은 Comparable 인터페이스를 구현하고 있으므로 List 타입 또한 compareTo 메서드를 기준으로 정렬된다.

public static <T extends Comparable<? super T>> void sort(List<T> list)

 

 

Integer.compare(a,b)

 - 두 정수 값을 비교하여 결과를 반환하는 메서드

 - a < b : 음수 반환

 - a > b : 양수 반환

 - a == b : 0 반환

 

Integer.compare() 을 사용하지 않고 아래와 같이 직접 구현할 수 도 있다.

@Override
public int compareTo(Person other){
	if(this.age < other.age){
    	return -1;
	} else if (this.age > other.age){
    	return 1;
    } else {
    	return 0;
    }
}

'algorithm' 카테고리의 다른 글

선택 정렬  (0) 2024.08.22
씨름 선수  (0) 2024.06.06
응급실  (0) 2024.06.05
교육과정 설계  (0) 2024.05.29
공주 구하기 / queue  (0) 2024.05.29
'algorithm' 카테고리의 다른 글
  • 선택 정렬
  • 씨름 선수
  • 응급실
  • 교육과정 설계
juuuuuuun
juuuuuuun
  • juuuuuuun
    namae
    juuuuuuun
  • 전체
    오늘
    어제
    • 분류 전체보기 (94)
      • java (2)
      • Infra (4)
      • server (2)
      • algorithm (52)
      • HTTP (8)
      • android (1)
      • baekjoon (16)
      • 소프트웨어공학 (6)
      • 기타 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
juuuuuuun
Comparable<T> 인터페이스
상단으로

티스토리툴바