Dart – Generics
Last Updated :
23 Nov, 2022
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:
Dart
main() {
List< int > listEx = [];
listEx.add(341);
listEx.add(1);
listEx.add(23);
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:
Dart
main() {
Set < int > SetEx = new Set < int >();
SetEx.add(12);
SetEx.add(3);
SetEx.add(4);
SetEx.add(3);
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:
Dart
main() {
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:
Dart
import 'dart:collection' ;
main() {
Queue< int > q = new Queue< int >();
q.addLast(1);
q.addLast(2);
q.addFirst(3);
q.addLast(4);
q.removeFirst();
for ( int element in q){
print(element);
}
}
|
Output:
1
2
4
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...