Java Program to Create the Clone of a HashSet Collection

Java program to create the clone of a HashSet collection

// Java program to create the clone of 
// the HashSet collection

import java.util.*;

public class Main {
  public static void main(String[] args) {
    HashSet < Integer > nums = new HashSet();

    nums.add(1);
    nums.add(2);
    nums.add(3);
    nums.add(4);

    HashSet < Integer > clone = (HashSet < Integer > ) nums.clone();

    System.out.println("Set items: ");
    Iterator < Integer > itr = nums.iterator();
    while (itr.hasNext()) {
      System.out.println(" " + itr.next());
    }

    System.out.println("Cloned Set items: ");
    Iterator < Integer > itr1 = clone.iterator();
    while (itr1.hasNext()) {
      System.out.println(" " + itr1.next());
    }
  }
}

Output

Set items: 
 1
 2
 3
 4
Cloned Set items: 
 1
 2
 3
 4
Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment