In the program, a HashSet named hash_set is created and populated with some elements: "Black", "White", "Pink", "Red", "Green", and "Yellow". The program then creates a new array arr with the same size as the HashSet using hash_set.size(). The toArray() method is called on the HashSet, passing the arr array as an argument. This method copies the elements from the HashSet into the array. Finally, the elements of the array are printed to the console using a for-each loop.
import java.util.*; public class HashSet_Array { public static void main(String[] args) { HashSet<String> hash_set = new HashSet<String>(); hash_set.add("Black"); hash_set.add("White"); hash_set.add("Pink"); hash_set.add("Red"); hash_set.add("Green"); hash_set.add("Yellow"); System.out.println("Hash Set : " + hash_set); String[] arr = new String[hash_set.size()]; hash_set.toArray(arr); System.out.println("Array Elements : "); for(String ele : arr) { System.out.println(ele); } } }
Hash Set : [Red, White, Pink, Yellow, Black, Green] Array Elements : Red White Pink Yellow Black Green
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions