Sub topic 3
Sorting and searching
This chapter assumes you know typed generics such as List<int>, nullable types such as int?, and the basic List, Map, and Set literals. It covers sorting, mutability, copying, equality, and the sorted collection variants.
Sorting and searching
sort() changes a list in place. To keep the original, sort a copy made with the spread operator.
void main() {
final scores = <int>[42, 7, 19, 88];
final sorted = [...scores]..sort();
print(sorted); // [7, 19, 42, 88]
print(sorted.indexOf(19)); // 1
print(sorted.indexWhere((n) => n > 40)); // 2
print(sorted.contains(100)); // false
}Growable, fixed-length, and const collections
A list literal is growable, so add works. A const list and a list made with List.filled both reject length changes by throwing UnsupportedError.
void main() {
const fixed = [1, 2, 3];
try {
fixed.add(4);
} on UnsupportedError {
print('const list cannot change');
}
final filled = List<int>.filled(3, 0);
filled[0] = 1; // element writes are allowed
try {
filled.add(4);
} on UnsupportedError {
print('fixed-length list cannot grow');
}
}Copying collections
The spread operator makes a shallow copy. The new outer list is independent, but nested objects are shared.
void main() {
final original = [[1, 2], [3]];
final shallow = [...original];
shallow[0].add(99);
print(original[0]); // [1, 2, 99]
shallow.add([4]);
print(original.length); // 2
}Equality and hashCode
Sets and map keys use == and hashCode to decide whether two values match. A class must override both. Lists use identity equality, so two lists with the same contents are still different keys.
class Point {
final int x;
final int y;
const Point(this.x, this.y);
@override
bool operator ==(Object other) =>
other is Point && other.x == x && other.y == y;
@override
int get hashCode => Object.hash(x, y);
}
void main() {
print({Point(1, 2), Point(1, 2)}.length); // 1
print([1, 2] == [1, 2]); // false
}Ordered and sorted variants
Map and set literals keep insertion order. SplayTreeMap and SplayTreeSet keep their keys sorted instead.
| Collection | Iteration order |
|---|---|
| `Map` or `Set` literal | Insertion order |
| `SplayTreeMap` or `SplayTreeSet` | Sorted by key |
import 'dart:collection';
void main() {
final m = SplayTreeMap<String, int>.from({'b': 2, 'a': 1});
print(m.keys); // (a, b)
}Choosing the right collection
Use this flow to pick a collection.
Exercise
Why does final sorted = [...scores]..sort(); leave scores unchanged?
Show answer
The spread creates a new list, so sort() changes only the copy.