Java HashSet clone()

In this guide, you will learn about the HashSet clone() method in Java programming and how to use it with an example.

1. HashSet clone() Method Overview


The clone() method of the HashSet class in Java returns a shallow copy of the HashSet instance: the elements themselves are not cloned.


public Object clone()


The method does not take any parameters.

Key Points:

- The clone() method creates a new HashSet instance and inserts all elements of the original set into the new set.

- Changes to the cloned HashSet instance do not affect the original HashSet instance and vice versa.

- The clone() method does not clone the elements themselves; it creates a new set containing references to the same elements.

- The method is not type-safe; it returns an object of type Object, so a type cast is needed to assign it to a HashSet variable.

- The clone() method is generally used to get a backup of the original object in memory.

2. HashSet clone() Method Example

import java.util.HashSet;

public class HashSetCloneExample {

    public static void main(String[] args) {
        HashSet<String> originalSet = new HashSet<>();

        // Adding elements to the original HashSet

        // Printing the original HashSet
        System.out.println("Original HashSet: " + originalSet);

        // Cloning the original HashSet
        HashSet<String> clonedSet = (HashSet<String>) originalSet.clone();

        // Printing the cloned HashSet
        System.out.println("Cloned HashSet: " + clonedSet);

        // Adding a new element to the cloned HashSet

        // Printing both HashSets after modification
        System.out.println("Original HashSet after modification: " + originalSet);
        System.out.println("Cloned HashSet after modification: " + clonedSet);


Original HashSet: [Banana, Cherry, Apple]
Cloned HashSet: [Banana, Cherry, Apple]
Original HashSet after modification: [Banana, Cherry, Apple]
Cloned HashSet after modification: [Date, Banana, Cherry, Apple]


In this example, we have an original HashSet containing some elements. 

We then clone this HashSet using the clone() method and make a modification to the cloned set by adding a new element. 

The output demonstrates that the original HashSet remains unaffected by changes to the cloned set, thereby showcasing that a shallow copy of the HashSet has been created.