Here is the program for converting a HashSet
to an array.
Program
import java.util.HashSet; class ConvertHashSettoArray{ public static void main(String[] args) { // Create a HashSet HashSet<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Element1"); hset.add("Element2"); hset.add("Element3"); hset.add("Element4"); // Displaying HashSet elements System.out.println("HashSet contains: "+ hset); // Creating an Array String[] array = new String[hset.size()]; hset.toArray(array); // Displaying Array elements System.out.println("Array elements: "); for(String temp : array){ System.out.println(temp); } } }
Output:
HashSet contains: [Element1, Element2, Element3, Element4] Array elements: Element1 Element2 Element3 Element4
Leave a Reply