![]() |
VOOZH | about |
HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass.
Given a HashMap, there are three ways one can copy the given HashMap to another:
Method 1: By normally iterating and putting it to another HashMap using put(k, v) Method.
A simple solution is to iterate through the map and use put(Key,Value) once for each mapping key and value in the another Map.
{A=1, B=2, C=3}Method 2: Using putAll(k, v) Method.
Map.putAll(k,v) method is used to copy one HashMap to another empty HashMap.
Syntax:
new_hash_map.putAll(exist_hash_map)
Parameters: The method takes one parameter exist_hash_map that refers to the existing map we want to copy from.
Return Value: The method does not return any values.
Exception: The method throws NullPointerException if the map we want to copy from is NULL.
{A=1, B=2, C=3}Method 3: Using copy constructor.
It is one of the shortest and easiest ways to copy one HashMap to another.
We can use a copy constructor to copy a map which is a special constructor for creating a new object as a copy of an existing object.
{A=1, B=2, C=3}Method 4 : Using Assignment Operator
In java, if both the objects are same then we can easily copy or assign one object elements to other by simply using assignment operator "=".
Output :
{A=1, B=2, C=3}