Java Utility Library

Java HashSet - clone() Method



The java.util.HashSet.clone() method returns a shallow copy of the given HashSet.

Syntax

public Object clone()

Parameters

No parameter is required.

Return Value

Returns a shallow copy of the given HashSet instance.

Exception

NA

Example:

In the example below, the java.util.HashSet.clone() method is used to create a shallow copy of the HashSet called MySet.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating hash set
    HashSet<Integer> MySet = new HashSet<Integer>();

    //populating hash set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    HashSet NewSet = new HashSet();
    NewSet = (HashSet) MySet.clone();

    //printing hashset
    System.out.println("NewSet contains: " + NewSet);
  }
}

The output of the above code will be:

NewSet contains: [40, 10, 20, 30]

❮ Java.util - HashSet