Java HashMap Clear Delete All Mappings Example

This example shows how to clear HashMap in Java or how to delete all key value mappings from the HashMap object using the clear method of the HashMap class.

How to clear HashMap in Java?

There are a couple of ways using which you can delete all mappings from the HashMap.

1. Using the clear method

The clear method of the HashMap class removes all key-value mappings from the HashMap object.

The clear method does not take any arguments and its return type is void. The HashMap object will be empty after this method call.


2. By assigning a new object

You can also assign a new empty HashMap object to the same reference.


What is the preferred way to clear the HashMap?

Let’s first have a look at the source code of the clear method.

The clear method iterates the internal table and makes each entry null. All the key value references are set to null so that they be can garbage collected if they are not referenced anywhere else.

When you assign a new HashMap object to the same reference, similar to the clear method, all the key value objects need to be garbage collected (if they are not referenced anywhere else) plus the original HashMap object. Additionally, a new map object needs to be created and assigned to the same reference.

The important difference is that when you use the clear method, the same HashMap object can be reused. But when you assign a new object to the same reference, a new object needs to be created which is a costly operation in terms of performance.

Plus, as you can see from the code above, when you use the clear method the HashMap capacity does not change. So if you are going to add a roughly similar number of mappings to the HashMap, the clear method has an advantage as the table does not need to increase the capacity.

This tutorial is a part of the Java HashMap tutorial with examples.

Please let me know your views in the comments section below.

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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