Java HashSet clone() Method (original) (raw)
Last Updated : 23 Jan, 2025
The HashSet clone() method in Java is used to return a shallow copy of the given HashSet. It just creates a copy of the set.
Syntax of HashSet clone() Method
public Object clone()
**Return Type: This method returns a new HashSet object that contains the same element as the original set.
**Example: This example demonstrates the use of the clone() method to **return a shallow copy of the HashSet.
Java `
//Java program to demonstrates the working of clone() import java.io.*; import java.util.HashSet;
public class Geeks { public static void main(String args[]) { // Creating an empty HashSet HashSet hs = new HashSet();
// Use add() method to add elements into the Set
hs.add("Geek1");
hs.add("Geek2");
hs.add("Geek3");
hs.add("Geek4");
System.out.println("HashSet: " + hs);
// Creating a new cloned set
HashSet cs = new HashSet();
// Cloning the set using clone() method
cs = (HashSet)hs.clone();
System.out.println("ClonedSet: " + cs);
}
}
`
Output
HashSet: [Geek4, Geek3, Geek2, Geek1] ClonedSet: [Geek3, Geek2, Geek1, Geek4]
**Note: The clone() method returns object and casting it to the desired type is necessary when assigning to a HashSet variable.