Menu
Coddy logo textTech

Comparable Interface

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 72 of 110.

While == tells you if two objects are equal, sometimes you need to know which one comes first. The Comparable interface lets your objects be sorted by defining a natural ordering.

To make a class comparable, implement Comparable<T> and override the compareTo method. This method returns a negative number if this comes before other, zero if they're equal, and a positive number if this comes after:

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
}

Once your class implements Comparable, you can use sort() without providing a custom comparator. The built-in numeric and string types already implement Comparable, which is why grade.compareTo(other.grade) works directly.

For descending order, simply reverse the comparison by swapping the objects or negating the result:

@override
int compareTo(Student other) {
  return other.grade.compareTo(grade);  // Descending
}
challenge icon

Challenge

Easy

Let's build a task management system where tasks can be sorted by their priority level! You'll create a Task class that implements the Comparable interface, allowing a list of tasks to be automatically sorted from highest to lowest priority.

You'll organize your code into two files:

  • task.dart: Create a Task class that represents a to-do item with a name (String) and priority (int, where higher numbers mean higher priority). Your task should implement Comparable<Task> so that when sorted, tasks appear in descending order by priority (highest priority first). Also override toString() to return the format: [name] (Priority: [priority])
  • main.dart: Import your task file and demonstrate how the Comparable interface enables automatic sorting. Create a list containing these four tasks:
    • 'Write report' with priority 2
    • 'Fix critical bug' with priority 5
    • 'Update documentation' with priority 1
    • 'Review code' with priority 3
    Print Before sorting:, then print each task. Sort the list using sort(), print an empty line, then print After sorting: followed by each task again.

Because your Task class implements Comparable, you can call sort() directly on the list without providing a custom comparator. The tasks will automatically arrange themselves based on your compareTo implementation!

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)

Cheat sheet

The Comparable interface allows objects to define a natural ordering for sorting. Implement Comparable<T> and override the compareTo method.

The compareTo method returns:

  • A negative number if this comes before other
  • Zero if they're equal
  • A positive number if this comes after other

Basic implementation (ascending order):

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

Once a class implements Comparable, you can use sort() without a custom comparator:

var students = [
  Student('Alice', 85),
  Student('Bob', 92),
  Student('Carol', 78),
];

students.sort();  // Automatically uses compareTo

For descending order, reverse the comparison:

@override
int compareTo(Student other) {
  return other.grade.compareTo(grade);  // Descending
}

Try it yourself

import 'task.dart';

void main() {
  // TODO: Create a list of Task objects with the following:
  // - 'Write report' with priority 2
  // - 'Fix critical bug' with priority 5
  // - 'Update documentation' with priority 1
  // - 'Review code' with priority 3
  
  List<Task> tasks = [
    // TODO: Add the four tasks here
  ];
  
  // TODO: Print "Before sorting:"
  // TODO: Print each task in the list
  
  // TODO: Sort the list using sort()
  
  // TODO: Print an empty line
  
  // TODO: Print "After sorting:"
  // TODO: Print each task in the sorted list
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming