How to Clone a Map in Java

The java.util.HashMap class is the Hash table based implementation of the Map interface. To clone a Map in Java, use the clone() method.


Let us see an example to clone a Map −

import java.util.*;
public class HashMapDemo {
   public static void main(String args[]) {
      // create two hash maps
      HashMap newmap1 = new HashMap();
      HashMap newmap2 = new HashMap();
      // populate 1st map
      newmap1.put(1, "This");
      newmap1.put(2, "is");
      newmap1.put(3, "it!");
      // clone 1st map
      newmap2 = (HashMap)newmap1.clone();
      System.out.println("1st Map: " + newmap1);
      System.out.println("Cloned Map: " + newmap2);


1st Map: {1=This, 2=is, 3=it!}
Cloned Map: {1=This, 2=is, 3=it!}

Updated on: 24-Sep-2019


Kickstart Your Career

Get certified by completing the course

Get Started