In Dart, by default collections are heterogeneous. However, by the use of generics, we can make a collection to hold homogeneous values. The use of Generics makes the use of a single compulsory data type to be held inside the collection. Such collections are called type-safe collections. By the use of generics, type safety is ensured in the Dart language.
Syntax:
Collection_name <data_type> identifier= new Collection_name<data_type>
We can use List, Set, Map, and Queue generics to implement type safety in Dart.
Generic List
In Dart, a List is simply an ordered group of objects. A list is simply an implementation of an array.
Example:
main() { List< int > listEx = [];
listEx.add(341);
listEx.add(1);
listEx.add(23);
// iterating across list listEx
for ( int element in listEx) {
print(element);
}
} |
Output:
341 1 23
Generic Set
In Dart, a Set represents a collection of objects in which each object can exist only once.
Example:
main() { Set < int > SetEx = new Set < int >();
SetEx.add(12);
SetEx.add(3);
SetEx.add(4);
// Already added once, hence wont be added
SetEx.add(3);
// iterating across Set SetEx
for ( int element in SetEx) {
print(element);
}
} |
Output:
12 3 4
Generic Map
In Dart, Map is a dynamic collection of the key, value pairs.
Example:
main() { // Creating a Map with Name and ids of students
Map <String, int > mp={ 'Ankur' :1, 'Arnav' :002, 'Shivam' :003};
print( 'Map :${mp}' );
} |
Output:
Map :{Ankur: 1, Arnav: 2, Shivam: 3}
Generic Queue
A queue is a collection that is used when the data is to be inserted in a FIFO (First in first out) manner. In Dart, a queue can be manipulated at both ends, i.e. at the start as well as the end of the queue.
Example:
import 'dart:collection' ;
main() { Queue< int > q = new Queue< int >();
// Inserting at end of the queue
q.addLast(1);
// Inserting at end of the queue
q.addLast(2);
// Inserting at start of the queue
q.addFirst(3);
// Inserting at end of the queue
q.addLast(4);
// Current Queue order is 3 1 2 4.
// Removing the first element(3) of the queue
q.removeFirst();
// Iterating over the queue
for ( int element in q){
print(element);
}
} |
Output:
1 2 4