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

The HashSet.clone() method is present in the HashSet class inside the java.util package. It returns the shallow copy of the given HashSet.

Let’s understand this with the help of an example. Suppose that the HashSet contains [1, 8, 5, 3, 0] elements. Upon using the hashSet.clone() method and storing the result in an object named clone, we get the copy of the HashSet.

Parameters

The HashSet.clone() doesn’t accept any parameters.

Return value

The HashSet.clone() returns the copy of the HashSet.

Code

Let’s have a look at the code:

import java.io.*;
import java.util.HashSet;
class Main
{
public static void main(String args[])
{
HashSet<Integer> hash_set1 = new HashSet<Integer>();
hash_set1.add(1);
hash_set1.add(8);
hash_set1.add(5);
hash_set1.add(3);
hash_set1.add(17);
HashSet clone = new HashSet();
clone = (HashSet)hash_set1.clone();
System.out.println("The clone of hash_set1 is: " + clone);
}
}

Explanation

  • In lines 1 and 2, we import the required packages and classes.

  • In line 4, we make the Main class.

  • In line 6, we make the main() function.

  • In line 8, we declare a HashSet of the integer type, i.e., hash_set1.

  • From lines 9 to 13, we add the elements into the HashSet using the HashSet.add() method.

  • In line 15, we make an object of HashSet, i.e., clone.

  • In line 16, we use the HashSet.clone() function to get the copy of hash_set1 and store it in the clone variable.

  • In line 18, we display the clone object with a message.

Free Resources