Write a Java program to Copy all elements from HashSet to an array


The program starts with the import statement import java.util.HashSet; , which imports the HashSet class from the java.util package.

  • The program defines a public class called CopyHashSet_ToArray. Within the CopyHashSet_ToArray class, the main method is declared and serves as the entry point for the program. It takes an array of strings (a) as input.
  • Inside the main method, a new instance of the HashSet class is created using the constructor: HashSet h = new HashSet();. The specifies the type of elements that will be stored in the HashSet, which in this case is a string.
  • After that, several elements are added to the HashSet h using the add() method. The elements added are "C", "JAVA", "CPP", "PYTHON", "MYSQL", and "RUBY".
  • Next, the program prints the contents of the HashSet h using the System.out.println() statement.
  • The program then creates an array of strings called arr with the same size as the HashSet h using the size() method. The size() method returns the number of elements in the HashSet.
  • The toArray() method is then used to copy all the elements from the HashSet h to the arr array.
  • Finally, the program prints the contents of the arr array using a for-each loop. It displays each element on a new line using the System.out.println() statement.

Source Code

import java.util.HashSet;
public class CopyHashSet_ToArray
{
	public static void main(String a[])
	{
		HashSet<String> h = new HashSet<String>();
		h.add("C");
		h.add("JAVA");
		h.add("CPP");
		h.add("PYTHON");
		h.add("MYSQL");
		h.add("RUBY");
		System.out.println("HashSet : "+h);
 
		String[] arr = new String[h.size()];
 
		h.toArray(arr);
 
		System.out.println("Copy all elements from HashSet to an Array : ");
		for(String e : arr)
		{
			System.out.println(e);
		}
	}
}

Output

HashSet : [JAVA, CPP, C, MYSQL, RUBY, PYTHON]
Copy all elements from HashSet to an Array :
JAVA
CPP
C
MYSQL
RUBY
PYTHON

Example Programs