Java HashMap clone() Method Example

The clone() method of java.util.HashMap class will return a shallow copy of this HashMap instance, the keys and values themselves are not cloned.

Signature

public Object clone()

This method returns a shallow copy of this HashMap instance, the keys and values themselves are not cloned.

Example

The following example shows the usage of java.util.HashMap.clone() method.

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

public class CloneMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create an empty HashMap
        HashMap<Integer,String>  hashMap1 = new HashMap<Integer,String>();
        
        // use put() method to put elements to the HashMap
        hashMap1.put(1,"Element1");
        hashMap1.put(2,"Element2");
        hashMap1.put(3,"Element3");
        hashMap1.put(4,"Element4");
        hashMap1.put(5,"Element5");
        
        //printing the elements of the hashMap1
        System.out.println("**Elements of the hashmap1**");
        for(Map.Entry<Integer,String> mapEntry : hashMap1.entrySet())
        {
            System.out.println("Key : "+mapEntry.getKey()+" Value : "+mapEntry.getValue());
        }
        
        HashMap<Integer,String> hashMap2 = (HashMap<Integer, String>)hashMap1.clone();
        
      //printing the elements of the hashMap2
        System.out.println("**Elements of the hashmap2 **");
        for(Map.Entry<Integer,String> mapEntry : hashMap2.entrySet())
        {
            System.out.println("Key : "+mapEntry.getKey()+" Value : "+mapEntry.getValue());
        }
    }
}

Output

**Elements of the hashmap1**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 4 Value : Element4
Key : 5 Value : Element5
**Elements of the hashmap2 **
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 4 Value : Element4
Key : 5 Value : Element5

Leave a Reply

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