Java Hashtable clone() Method Example

The clone() method of java.util.Hashtable class will reate a shallow copy of this hashtable. All the structure of the hashtable itself is copied, but the keys and values are not cloned. This is a relatively expensive operation.

Signature

public Object clone()

This method creates a shallow copy of this hashtable. All the structure of the hashtable itself is copied, but the keys and values are not cloned. This is a relatively expensive operation.

Example

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

import java.util.Hashtable;
import java.util.Map;

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

Output

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

Leave a Reply

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