Write a Java program to get a shallow copy of a HashMap instance


This is a Java program that demonstrates how to create a shallow copy of a HashMap using the clone() method. Here's how it works:

  • First, a HashMap object is created using the HashMap class. This HashMap will be used to store integer keys and string values.
  • Key-value pairs are added to the HashMap using the put() method.
  • The contents of the HashMap are printed to the console using the println() method.
  • A new HashMap object is created using the HashMap class. This will be used to store the shallow copy of the original HashMap.
  • The clone() method is called on the original HashMap object, and the result is stored in the new HashMap object. This creates a shallow copy of the original HashMap.
  • The contents of the new HashMap are printed to the console using the println() method.

Source Code

import java.util.*;  
public class Shallow_Copy
{  
	public static void main(String args[])
	{  
		HashMap<Integer,String> hash_map = new HashMap<Integer,String>();  
		hash_map.put(1, "Pink");
		hash_map.put(2, "Green");
		hash_map.put(3, "Red");
		hash_map.put(4, "White");
		hash_map.put(5, "Blue");
		hash_map.put(6, "Black");
		hash_map.put(7, "Orange");		
		System.out.println("HashMap : " + hash_map);
 
		HashMap<Integer,String> new_hashmap = new HashMap<Integer,String>();	
		new_hashmap = (HashMap)hash_map.clone();     
		System.out.println("Cloned HashMap : " + new_hashmap);        
	}
}

Output

HashMap : {1=Pink, 2=Green, 3=Red, 4=White, 5=Blue, 6=Black, 7=Orange}
Cloned HashMap : {1=Pink, 2=Green, 3=Red, 4=White, 5=Blue, 6=Black, 7=Orange}