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
HashMapInteger, String> hashmap = new HashMapInteger, 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
HashMapInteger, String> hashmap2 = new HashMapInteger, String>();
// cloning first HashMap in the second one
hashmap2=(HashMap)hashmap.clone();
System.out.println("Cloned Map contains: "+hashmap2);
}
}
Output
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}