How to create HashMap in Java, HashMap Constructors

This example shows how to create a HashMap object in Java using various HashMap constructors. This example also shows how to copy HashMap to another HashMap object.

How to create a HashMap object in Java?

The HashMap class in Java provides several constructors to create its objects.

1. Create an empty HashMap object

The default constructor of the HashMap class creates an empty HashMap object.

This constructor creates an empty HashMap object with the default capacity of 16 and a load factor of 0.75.

The above statement will create an empty HashMap object whose keys and values will be of type String.

2. With specified initial capacity and load factor

There are two overloaded constructors using which you can specify the initial capacity and load factor of the map object.

This constructor creates an empty map with the specified initial capacity instead of the default 16.

This constructor creates an empty map with the specified initial capacity and load factor instead of default 16 and 0.75 respectively.

3. From another HashMap (or any other Map)

The HashMap class provides an overloaded constructor that accepts the Map object.

This constructor creates a new HashMap object having the same mappings as the specified map object. The load factor of the new map will be 0.75 while the initial capacity will be enough to hold the mappings of the specified argument map object.

You can use this constructor to create a HashMap object from another HashMap object (i.e. copy HashMap) or TreeMap object.

The below given example shows how to copy HashMap to another HashMap object using this constructor.

Output

You can also copy a TreeMap object (or any other Map implementation) to the HashMap object using this constructor.

This example is a part of the Java HashMap tutorial.

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

About the author

RahimV

RahimV

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 *