Menu
Coddy logo textTech

Comparable 인터페이스

Coddy Dart 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 110개 중 72번째.

==는 두 객체가 같은지 알려 주지만, 때로는 어느 객체가 먼저 오는지 알아야 합니다. Comparable 인터페이스를 사용하면 자연 순서를 정의하여 객체를 정렬할 수 있습니다.

class를 비교 가능하게 만들려면 Comparable<T>을 implement하고 compareTo method를 override하세요. 이 method는 thisother보다 앞에 오면 음수를, 둘이 같으면 0을, thisother보다 뒤에 오면 양수를 반환합니다:

class Student implements Comparable<Student> {
  String name;
  int grade;
  
  Student(this.name, this.grade);
  
  @override
  int compareTo(Student other) {
    return grade.compareTo(other.grade);
  }
}

void main() {
  var students = [
    Student('Alice', 85),
    Student('Bob', 92),
    Student('Carol', 78),
  ];
  
  students.sort();
  
  for (var s in students) {
    print('${s.name}: ${s.grade}');
  }
  // Carol: 78, Alice: 85, Bob: 92
}

클래스가 Comparable을 구현하면 사용자 지정 비교 함수를 제공하지 않고도 sort()를 사용할 수 있습니다. 기본 제공 숫자 및 문자열 형식은 이미 Comparable을 구현하므로 grade.compareTo(other.grade)가 직접 작동합니다.

descending order의 경우, objects를 서로 바꾸거나 결과를 부정하여 comparison을 간단히 반대로 하면 됩니다:

@override
int compareTo(Student other) {
  return other.grade.compareTo(grade);  // 내림차순
}
challenge icon

챌린지

쉬움

작업을 우선순위 수준에 따라 정렬할 수 있는 작업 관리 시스템을 만들어 봅시다! Comparable 인터페이스를 구현하는 Task class를 만들고, 작업 목록이 높은 우선순위부터 낮은 우선순위 순으로 Automatically 정렬되도록 합니다.

코드를 두 개의 파일로 구성합니다:

  • task.dart: name(String)과 priority(int, 숫자가 높을수록 우선순위가 높음을 의미)를 가진 할 일 항목을 나타내는 Task class를 Create합니다. 정렬할 때 작업이 priority의 Descending order(가장 높은 priority가 first)로 표시되도록 Comparable<Task>를 Implement해야 합니다. 또한 toString()을 override하여 다음 형식을 반환하도록 합니다: [name] (Priority: [priority])
  • main.dart: task 파일을 import하고 Comparable 인터페이스가 Automatically 정렬을 가능하게 하는 방법을 보여 줍니다. 다음 four 작업을 포함하는 list를 만듭니다:
    • 'Write report', priority 2
    • 'Fix critical bug', priority 5
    • 'Update documentation', priority 1
    • 'Review code', priority 3
    Before sorting:을 Print한 다음 각 작업을 Print합니다. sort()를 사용하여 list를 정렬하고, empty line을 Print한 다음 After sorting:을 Print하고 각 작업을 다시 Print합니다.

Task classComparable을 Implement하므로 custom comparator를 제공하지 않고 list에서 직접 sort()를 호출할 수 있습니다. 작업은 compareTo 구현에 따라 Automatically 정렬됩니다!

Expected output:

Before sorting:
Write report (Priority: 2)
Fix critical bug (Priority: 5)
Update documentation (Priority: 1)
Review code (Priority: 3)

After sorting:
Fix critical bug (Priority: 5)
Review code (Priority: 3)
Write report (Priority: 2)
Update documentation (Priority: 1)

직접 해보기

import 'task.dart';

void main() {
  // TODO: 다음과 같은 Task 객체 목록을 생성하세요:
  // - 'Write report' 우선순위 2
  // - 'Fix critical bug' with priority 5
  // - 'Update documentation' with priority 1
  // - 'Review code' 우선순위 3
  
  List<Task> tasks = [
    // TODO: 여기에 네 개의 작업을 추가하세요
  ];
  
  // TODO: Print "Before sorting:"
  // TODO: 목록의 각 작업을 출력하세요
  
  // TODO: sort()를 사용하여 목록을 정렬하세요
  
  // TODO: 빈 줄을 출력하세요
  
  // TODO: Print "After sorting:"
  // TODO: 정렬된 목록의 각 작업을 출력하세요
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Dart 컴파일러