What is the HashMap.clear() method in Dart?
Overview
The clear method can be used to remove all entries from a HashMap object. After calling this method, the HashMapobject becomes empty.
Note: Read more about the
HashMapclass here.
Syntax
void clear()
This method doesn’t take any argument and doesn’t return any value.
Example
The code below demonstrates how to remove all the entries present in the HashMap object below.
import 'dart:collection';void main() {//create a new hashmap which can have string type as key, and int type as valueHashMap map = new HashMap<String, int>();// add two entries to the mapmap["one"] = 1;map["two"] = 2;print('The map is $map');// clear the entries of the mapmap.clear();print('After calling clear method. The map is $map');}
Explanation
-
Line 1: We import the
collectionlibrary. -
Line 4: We create a new
HashMapobject with the namemap. -
Lines 7–8: We add two new entries to the
map. -
Line 12: We use the
clearmethod to remove all the entries present inmap. As a result,mapbecomes empty.