java.util.HashMap clear()

Description :

On this document we will be showing a java example on how to use the clear() method of HashMap Class. Basically this method is to delete all key value pair mapping on the HashMap. After invoking this method, the HashMap will be empty thus calling the isEmpty() method will return true. Why we want to empty our HashMap? Where there are situations wherein we want to reuse the existing HashMap and we don’t want to include it to the existing key-value pair mapping, thus calling clear() method will do the job.

Important notes for put(K key, V value) method:

  • specified by clear in interface Map<K,V>
  • overrides clear in class AbstractMap<K,V>

Method Syntax :

public void clear()

Parameter Input :


Method Returns :

The put method returns void.

Compatibility Version :

Requires Java 1.2 and up

Exception :


Java Code Example :

This java example source code demonstrates the use of clear() method of HashMap class.  Let’s discuss one by one on the code logic that we have used on the example. First we have declared a HashMap with String as key and String as value  HashMap<String, String> mapEmployee = init(); . So basically we have a key value mapping of employees with their corresponding employee id as keys. After which we have check the map size. The clear() method were called to remove all the contents of the mapStudent HashMap. A check is in place to to check if the HashMap is empty and we print a message saying that the map is having no key value mapping.

Sample Output :

Running the above java example of the usage of HashMap clear() method will give the following output:

HashMap clear example output

HashMap clear example output

As you can see from the output there are two messages. First message is printing the current size of the hashmap while the second message is saying the HashMap is empty. The second message is like that because it has been printed after we have called the method clear() which basically remove all the key value mapping.

Similar Method :

The following are the list of method that you can go through for better understanding of the presented example

  • HashMap put()
  • HashMap isEmpty()
  • HashMap size()

Suggested Reading List :

The following are the recommended reading materials for further understanding of HashMap

References :