What is the HashTable.clone() method in Java?

The HashTable.clone() method is present in the HashTable class inside the java.util package. It is used to return the shallow copy of the given HashTable.

Parameters

HashTable.clone() does not take any parameters.

Return

HashTable.clone() returns the copy of HashTable.

Example

Let’s go over this with the help of an example.

Suppose we have a HashTable1 = {1 = Let's, 5 = see, 2 = Hashtable.clone(), 27 = method}

Upon using the HashTable.clone() method, we store the result in the object clone of HashTable1, and it returns the copy of HashTable1 and stores it in clone.

Code

Let’s look at the below code snippet to understand it better.

import java.util.*;
class Main
{
public static void main(String[] args)
{
Hashtable<Integer, String> h1 = new Hashtable<Integer, String>();
h1.put(1, "Let's");
h1.put(5, "see");
h1.put(2, "Hashtable.clone()");
h1.put(27, "method");
h1.put(9, "in java.");
System.out.println("The Hashtable is: " + h1);
System.out.println("The clone of specified HashTable is: " + h1.clone());
}
}

Explanation

  • In line 1, we import the required package.
  • In line 2, we make a Main class.
  • In line 4, we make a main function.
  • In line 6, we declare a HashTable consisting of Integer type keys and string type values.
  • In lines 8 to 12, we insert values in the Hashtable by using the Hashtable.put() method.
  • In line 14, we display the original Hashtable.
  • In line 15, we use the HashTable.clone() method to create the clone of HashTable and display the clone HashTable with a message.

In this way, we can use the HashTable.clone() method to return the shallow copy of the given HashTable.

Free Resources