Java HashMap clone() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, clone() creates a new HashMap holding the same mappings as the original. Adding, removing, or replacing mappings in one map does not affect the other.

The copy is shallow: the keys and value objects themselves are not copied. If a value is mutable, such as a List, both maps share it, so changing the list through one map is visible through the other.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety.

Syntax

clone() returns Object, so cast the result. The variable must be a HashMap, not a Map.

Java
HashMap<String, Integer> prices = new HashMap<>();
prices.put("tea", 30);
@SuppressWarnings("unchecked")
HashMap<String, Integer> copy = (HashMap<String, Integer>) prices.clone();
CallWhat it does
(HashMap<K, V>) map.clone()Shallow copy; needs a cast.
new HashMap<>(map)Shallow copy from any Map, no cast.
copy.putAll(map)Copies mappings into an existing map.

clone() is not declared in the Map interface, so Map<K, V> m cannot call it. Most code uses the copy constructor new HashMap<>(map) instead.

Library declarations
Java
// java.util.HashMap<K, V>
public Object clone()

// HashMap implements Cloneable

Parameters

ParameterDescription
Noneclone() takes no parameters.

Return Value

Return ValueDescription
ObjectA new HashMap with the same mappings. Cast it to HashMap<K, V>.

Compare with Similar Methods

Copying a HashMap:

MethodHow it differs
putAll(m)Copies mappings into a map you already have.
clear()Empties a map; a clone taken before keeps its entries.
entrySet()Loop over it to build a deep copy.

Java Examples

Example 1 — Clone a Price List and Change the Copy

Change a price and add an item in the clone; the original stays as it was.

Java
import java.util.HashMap;

public class HashMapCloneDemo {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        HashMap<String, Integer> prices = new HashMap<>();
        prices.put("tea", 30);
        prices.put("coffee", 45);

        HashMap<String, Integer> copy = (HashMap<String, Integer>) prices.clone();
        copy.put("tea", 35);
        copy.put("juice", 50);

        System.out.println("original: " + prices);
        System.out.println("copy:     " + copy);
        System.out.println("same object? " + (copy == prices));
    }
}

How It Works

  1. Cast required. clone() is declared to return Object, so the result is cast back to HashMap<String, Integer>; the annotation on main hides the unchecked warning.
  2. Separate structure. Putting a new tea price and a juice entry into copy changes only the copy's own table.
  3. Original intact. prices still holds tea=30 and no juice.
  4. Two objects. copy == prices is false: the clone is a brand-new map object.

Example 2 — Shared List Values in a Shallow Copy

Clone a map of class lists, change a list through the clone, and then build a deep copy that really is separate.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class HashMapCloneShallow {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        HashMap<String, List<String>> classes = new HashMap<>();
        classes.put("math", new ArrayList<>());
        classes.get("math").add("Ana");

        HashMap<String, List<String>> copy = (HashMap<String, List<String>>) classes.clone();
        copy.get("math").add("Ben");
        copy.put("art", new ArrayList<>());

        System.out.println("original math: " + classes.get("math"));
        System.out.println("same list? " + (copy.get("math") == classes.get("math")));
        System.out.println("original has art? " + classes.containsKey("art"));

        HashMap<String, List<String>> deep = new HashMap<>();
        for (String key : classes.keySet()) {
            deep.put(key, new ArrayList<>(classes.get(key)));
        }
        deep.get("math").add("Cy");
        System.out.println("after deep copy change: " + classes.get("math") + " vs " + deep.get("math"));
    }
}

How It Works

  1. Values are shared. The clone stores a reference to the very same ArrayList, so adding Ben through copy also shows up in classes.
  2. Proof by ==. Comparing the two lists with == gives true: one list object, two maps pointing at it.
  3. Structure is separate. The new "art" key exists only in the clone, so the original does not contain it.
  4. Deep copy by hand. Copying every list with new ArrayList<>(...) gives the new map its own lists, so adding Cy leaves the original unchanged.

Example 3 — clone() vs new HashMap<>(map)

Copy a room list with the copy constructor, clone it as well, and compare the results.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapCloneVsCopy {
    public static void main(String[] args) {
        Map<Integer, String> rooms = new HashMap<>();
        rooms.put(101, "Ali");
        rooms.put(102, "Bo");
        rooms.put(103, "Cai");

        // rooms.clone() does not compile: Map has no public clone()
        Map<Integer, String> copyA = new HashMap<>(rooms);

        HashMap<Integer, String> concrete = new HashMap<>(rooms);
        Object raw = concrete.clone();
        @SuppressWarnings("unchecked")
        Map<Integer, String> copyB = (Map<Integer, String>) raw;

        copyA.remove(101);
        System.out.println("rooms: " + rooms);
        System.out.println("copyA: " + copyA);
        System.out.println("copyB equals rooms? " + copyB.equals(rooms));
        System.out.println("clone() returns " + raw.getClass().getSimpleName());
    }
}

How It Works

  1. Interface type blocks clone. rooms is declared as Map, which does not expose clone(), so the copy constructor is the natural choice.
  2. Independent copies. Removing room 101 from copyA leaves rooms with all three rooms.
  3. Same contents. copyB.equals(rooms) compares mappings, not order or identity, and is true.
  4. Runtime class. The object returned by clone() is a real HashMap, which getSimpleName() confirms.

Frequently Asked Questions

Call (HashMap<K, V>) map.clone() on a HashMap variable, or more commonly use new HashMap<>(map).
No. It is a shallow copy: keys and values are shared, so mutable values such as lists are changed in both maps.
clone() returns Object and generic types are erased at run time, so the cast to HashMap<K, V> cannot be checked. Add @SuppressWarnings("unchecked") if you are sure.
The copy constructor new HashMap<>(map) is usually preferred: it needs no cast and accepts any Map.
Create a new map and put a copy of each value, for example new ArrayList<>(list) for list values.

Next: compute()

Compute a new value from the key and its current value.

compute() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful