Book Image

Mastering Dart

By : Sergey Akopkokhyants
Book Image

Mastering Dart

By: Sergey Akopkokhyants

Overview of this book

Table of Contents (19 chapters)
Mastering Dart
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Ordering of elements


Several collections implicitly support ordering of elements and help in sorting them without any effort. We can find any element with or without the filter predicate or perform a binary search within a sorted array to improve the performance of large collections. We can sort collections by providing a collection-compare function via a comparator or an object-compare method via the Comparable interface.

The Comparable interface

There are many core classes in Dart that support a native comparison via the implementation of the Comparable interface. You can implement the Comparable interface in classes that you have created to use them in collections to prevent unusual results of the sorting operation. Here, we will modify the Entity class to implement the Comparable interface. All we have to do is implement the compareTo method as shown in the following code:

class Entity implements Comparable {
  final int index;

  Entity(this.index);

  int compareTo(Entity other) {
  ...