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 HashMap class 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 value
HashMap map = new HashMap<String, int>();
// add two entries to the map
map["one"] = 1;
map["two"] = 2;
print('The map is $map');
// clear the entries of the map
map.clear();
print('After calling clear method. The map is $map');
}

Explanation

  • Line 1: We import the collection library.

  • Line 4: We create a new HashMap object with the name map.

  • Lines 7–8: We add two new entries to the map.

  • Line 12: We use the clear method to remove all the entries present in map. As a result,map becomes empty.

Free Resources