We can use the java.util.HashMap.clone()
method to create a shallow copy of any specified HashMap, meaning that no new HashMap is created. Instead, a reference for the original HashMap is made. This shallow copy refers to the clone of a HashMap.
Hash_Map.clone()
This method does not have any parameters.
This method returns a copy of a HashMap.
Take a look at the coding example of how to use this method to clone a HashMap, below.
// import the util lib from Javaimport java.util.*;class HelloWorld {public static void main( String args[] ) {{// Creating an empty HashMap based on our dataHashMap<Integer, String> fruit_prices = new HashMap<Integer, String>();// Introduce some data in the hashmapfruit_prices.put(10, "Apple");fruit_prices.put(20, "Banana");fruit_prices.put(30, "Orange");// Lets have a look at the HashMapSystem.out.println("Hashmap: "+ fruit_prices);// Lets have a look a look at the hashmap after applying cloneSystem.out.println("After applying clone method: " + fruit_prices.clone());}}}
Free Resources