Write a Java program to clone a hash set to another hash set


In the program, a HashSet named h_set is created and populated with some elements: "C", "JAVA", "CPP", "PYTHON", "MYSQL", and "RUBY". The program then creates a new HashSet named clone_set and assigns it the cloned contents of h_set using the clone() method. The clone() method creates a shallow copy of the HashSet. Finally, the contents of the original HashSet h_set and the cloned HashSet clone_set are printed to the console.

In the program, a HashSet named h_set is created and populated with some elements: "C", "JAVA", "CPP", "PYTHON", "MYSQL", and "RUBY". The program then creates a new HashSet named clone_set and assigns it the cloned contents of h_set using the clone() method. The clone() method creates a shallow copy of the HashSet. Finally, the contents of the original HashSet h_set and the cloned HashSet clone_set are printed to the console.

Source Code

import java.util.*;
public class Clone_HashSet
{
	public static void main(String[] args)
	{
		HashSet<String> h_set = new HashSet<String>();
		h_set.add("C");
		h_set.add("JAVA");
		h_set.add("CPP");
		h_set.add("PYTHON");
		h_set.add("MYSQL");
		h_set.add("RUBY");
		System.out.println("Given HashSet : " + h_set);
		HashSet<String> clone_set = new HashSet<String>();
		clone_set = (HashSet)h_set.clone();
		System.out.println("Clone HashSet : " + clone_set);         
	}
}

Output

Given HashSet : [JAVA, CPP, C, MYSQL, RUBY, PYTHON]
Clone HashSet : [JAVA, CPP, C, MYSQL, RUBY, PYTHON]

Example Programs