Home > Tutorial > Java HashMap Copy Sample

Java HashMap Copy Sample

Java HashMap copy operation to copy an existing HashMap to a new HashMap can be done in a few different ways. The first option is to construct a new HashMap and pass the exiting HashMap as the constructor argument. The second option is to use the HashMap.clone() method to make a clone or copy.


Java HashMap Copy Source Code

package com.jcd.java.tutorials;

import java.util.HashMap;

public class JavaHashMapCopy 
{

	public static void main(String[] args) 
	{
		
		//Define an empty HashMap (name/age)
		HashMap<String,Integer> jcdHashMap = new HashMap<String,Integer>();
		
		//Add random key/value pairs to the HashMap (name/age)
		jcdHashMap.put("Fred", 40);
		jcdHashMap.put("Barney", 38);
		jcdHashMap.put("Wilma", 39);
		jcdHashMap.put("Betty", 36);
		jcdHashMap.put("Bammbamm", 4);
		jcdHashMap.put("The Great Gazoo", 50);
		
		//Print out current key/values of original HashMap
		System.out.println("jcdHashMap: "+jcdHashMap);
		System.out.println("Size: "+jcdHashMap.size());
		System.out.println();
		
		//Create a shallow copy of our HashMap
		HashMap<String,Integer> jcdHashMapCopyA = new HashMap<String,Integer>(jcdHashMap);
		
		//Print out current key/values of original HashMap
		System.out.println("jcdHashMapCopyA: "+jcdHashMapCopyA);
		System.out.println("Size: "+jcdHashMapCopyA.size());
		System.out.println();
		
		//Create an empty HashMap
		HashMap<String,Integer> jcdHashMapCopyB = new HashMap<String,Integer>();
		
		//Copy the original HashMap to our new HashMap using clone() method
		jcdHashMapCopyB = (HashMap) jcdHashMap.clone();
		
		//Print out current key/values of original HashMap
		System.out.println("jcdHashMapCopyB: "+jcdHashMapCopyB);
		System.out.println("Size: "+jcdHashMapCopyB.size());
		
	}

}


Java HashMap Copy Output

jcdHashMap: {Barney=38, Wilma=39, Bammbamm=4, Betty=36, The Great Gazoo=50, Fred=40}
Size: 6

jcdHashMapCopyA: {Barney=38, Wilma=39, Bammbamm=4, Betty=36, The Great Gazoo=50, Fred=40}
Size: 6

jcdHashMapCopyB: {Barney=38, Wilma=39, Bammbamm=4, Betty=36, The Great Gazoo=50, Fred=40}
Size: 6


Smedley
Posted by

Smedley

Smedley has been programming in Java for about twenty years. He enjoys sharing code samples to other fellow Java coders.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot