CodeBlanks Logo Icon CodeBlanks

Generic collections

Learn List<T> and Map<K,V> generic collections.

Generic collections

Dart's built-in collections are generic. List<T> gives an ordered sequence, Map<K, V> a key-value store, Set<T> a unique set. The type parameter states which element type the collection holds.

Example: Map<String, int> ages = {'Ayşe': 28, 'Alex': 30};. Here keys are String, values are int. ages['Ayşe'] returns an int; reading the wrong type is prevented by type-safe access. Generic collections fix the element type at compile time; this stops wrong types in loops and method calls.

Nested generic collections

The type parameter of a generic collection can itself be generic. This is the way to build nested structures.

Example: List<List<int>> grid = [[1, 2], [3, 4]];. Here the outer list is a list whose elements are List<int>; a two-dimensional table of numbers. grid[0] gives the first row, grid[0][1] gives the second element of the first row. In the same way structures like Map<String, List<int>> can be built. Nested generics are the powerful tool to express real data models in a type-safe way.

Practice Work with a generic Map

In main, declare a Map<String, int> ages variable and initialize it with {'Ayşe': 28, 'Alex': 30}. Then call print(ages['Ayşe']).

Starter code

main.dart
// Declare a Map<String, int>
// print ages['Ayşe']

void main() {
}

Sample solution

main.dart
// Declare a Map<String, int>
void main() {
  Map<String, int> ages = {'Ayşe': 28, 'Alex': 30};
  print(ages['Ayşe']);
}

Expected output

28

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a generic collection declaration?

  • List<String> names = []; Correct answer
  • String s = 'a';
  • var z = 10;
  • int x = 5;

Explanation: List<String> is a generic collection with a type parameter.

2 Complete the Map declaration

Question
Map____ ages = {'Ayşe': 28};
Answer
Map<String, int> ages = {'Ayşe': 28};

Explanation: Map<String, int> makes keys String and values int.

3 Match the collection types

Term Meaning
List<T> Ordered sequence
Map<K, V> Key-value store
Set<T> Unique set

All lessons in Intermediate