HashMap clear() Method in Java

Published by user on

The clear() method of HashMap removes all the mappings from the map. After a call to the clear method, the HashMap becomes empty and the size of a map effectively becomes zero.

There is no way to get back the elements once the clear operation is complete. This method is useful when you want to remove all the elements at once.

The clear() method enables users to reuse the same instance of HashMap multiple times.

Some implementations of Map don’t support this method.

Method Signature

public void clear()

Parameters

It does not accept any parameter.

Return Value

It does not return any value.

Program

import java.util.HashMap;
import java.util.Map;

// This program shows
// how to remove all the entries
// using clear method
public class HashMapClear {
        public static void main(String[] args) {

                // Create a HashMap
                Map map = new HashMap();

                // Add elements to the map
                map.put(101, "John");
                map.put(102, "Adam");
                map.put(103, "Ricky");
                map.put(104, "Chris");

                System.out.println("Size of map : " + map.size());
                System.out.println("Map elements : " + map);

                // Clear all mappings
                map.clear();

                System.out.println("Size of map after a call to clear : " + map.size());
                System.out.println("Map elements after clear: " + map);
        }
}

Output

Size of map : 4
Map elements : {101=John, 102=Adam, 103=Ricky, 104=Chris}
Size of map after a call to clear : 0
Map elements after clear: {}

Explanation

  1. Create a new instance of a HashMap
  2. Add elements to it, at this point the size is greater than zero
  3. Call clear() method
  4. At this point, there are no elements in the map and the size becomes zero
  5. Before calling the clear() method, please ensure that you never want to access those elements
Categories: Java

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *