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.
1 |
public HashMap() |
This constructor creates an empty HashMap object with the default capacity of 16 and a load factor of 0.75.
1 |
HashMap<String, String> hmap = new HashMap<String, String>(); |
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.
1 |
public HashMap(int initialCapacity) |
This constructor creates an empty map with the specified initial capacity instead of the default 16.
1 |
public HashMap(int initialCapacity, float loadFactor) |
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.
1 |
public HashMap(Map<? extends K,? extends V> map) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.HashMap; public class CreateHashMapExample { public static void main(String[] args) { HashMap<Integer, String> hmapOriginal = new HashMap<Integer, String>(); hmapOriginal.put(1, "One"); hmapOriginal.put(2, "Two"); hmapOriginal.put(3, "Three"); /* * To copy all mappings of HashMap to another * HashMap use the constructor */ //create HashMap copy HashMap<Integer, String> hmapCopy = new HashMap(hmapOriginal); System.out.println("Original HashMap contains: " + hmapOriginal); System.out.println("Copied HashMap contains: " + hmapCopy); } } |
Output
1 2 |
Original HashMap contains: {1=One, 2=Two, 3=Three} Copied HashMap contains: {1=One, 2=Two, 3=Three} |
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.