How to Clone a HashMap in Java with Example

In the last tutorial I have shared how to get value from key example. In this post we will see how to clone a HashMap program in java. HashMap can be cloned using clone() method.

Syntax :

public Object clone() :

According to Oracle docs, it returns a shallow copy of the HashMap instance : the keys and values themselves are not cloned.

Program to Clone a HashMap in Java

import java.util.*;

 public class HashMapCloneExample {
    public static void main(String args[]) {
    // Creating a HashMap of Integer keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
    hashmap.put(1, "Value1");
    hashmap.put(2, "Value2");
    hashmap.put(3, "Value3");
    hashmap.put(4, "Value4");
    hashmap.put(5, "Value5");
    System.out.println("HashMap contains: "+hashmap);
     // Creating a new HashMap
     HashMap<Integer, String> hashmap2 = new HashMap<Integer, String>(); 
     // cloning first HashMap in the second one
     System.out.println("Cloned Map contains: "+hashmap2); 

HashMap contains: {1=Value1, 2=Value2, 3=Value3, 4=Value4, 5=Value5}
Cloned Map contains: {1=Value1, 2=Value2, 3=Value3, 4=Value4, 5=Value5}

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry