A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/hashset-clone-method-in-java/ below:

Java HashSet clone() Method - GeeksforGeeks

Java HashSet clone() Method

Last Updated : 11 Jul, 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<String> hs = new HashSet<String>();

        // 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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4