1. 程式人生 > >Clone a HashMap in Java

Clone a HashMap in Java

zz:https://beginnersbook.com/2014/08/clone-a-hashmap-in-java/
Description
A program to clone a HashMap. We will be using following method of HashMap class to perform cloning.
public Object clone(): Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.

Example
import java.util.HashMap;
class HashMapExample{

public static void main(String args[]) {

 // Create a HashMap
 HashMap<Integer, String> hmap = new HashMap<Integer, String>(); 


 // Adding few elements
 hmap.put(11, "Jack");
 hmap.put(22, "Rock");
 hmap.put(33, "Rick");
 hmap.put(44, "Smith");
 hmap.put(55, "Will");

 System.out.println("HashMap contains: "+hmap);

 // Creating a new HashMap
 HashMap<Integer, String> hmap2 = new HashMap<Integer, String>(); 

 // cloning first HashMap in the second one
 hmap2=(HashMap)hmap.clone();

 System.out.println("Cloned Map contains: "+hmap2); 

}
}
Output:

HashMap contains: {33=Rick, 55=Will, 22=Rock, 11=Jack, 44=Smith}
Cloned Map contains: {33=Rick, 55=Will, 22=Rock, 11=Jack, 44=Smith}