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
EasyLet'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 aTaskclass that represents a to-do item with aname(String) andpriority(int, where higher numbers mean higher priority). Your task should implementComparable<Task>so that when sorted, tasks appear in descending order by priority (highest priority first). Also overridetoString()to return the format:[name] (Priority: [priority])main.dart: Import your task file and demonstrate how theComparableinterface enables automatic sorting. Create a list containing these four tasks:'Write report'with priority2'Fix critical bug'with priority5'Update documentation'with priority1'Review code'with priority3
Before sorting:, then print each task. Sort the list usingsort(), print an empty line, then printAfter 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
thiscomes beforeother - Zero if they're equal
- A positive number if
thiscomes afterother
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 compareToFor 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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor