What is HashMap clone() in Java?

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.

Syntax

Hash_Map.clone()

Parameters and Return Value

Parameters

This method does not have any parameters.

Return value

This method returns a copy of a HashMap.

Code

Take a look at the coding example of how to use this method to clone a HashMap, below.

// import the util lib from Java
import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
{
// Creating an empty HashMap based on our data
HashMap<Integer, String> fruit_prices = new HashMap<Integer, String>();
// Introduce some data in the hashmap
fruit_prices.put(10, "Apple");
fruit_prices.put(20, "Banana");
fruit_prices.put(30, "Orange");
// Lets have a look at the HashMap
System.out.println("Hashmap: "+ fruit_prices);
// Lets have a look a look at the hashmap after applying clone
System.out.println("After applying clone method: " + fruit_prices.clone());
}
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved