1. Introduction
A HashSet is a collection of items where every item is unique, and it is part of the Java Collections Framework. There might be situations where we need to convert a HashSet to an array. In Java, this can be achieved using the toArray method.
2. Program Steps
1. Create and populate a HashSet with elements.
2. Convert the HashSet to an array using the toArray method.
3. Print the elements of the array.
3. Code Program
import java.util.HashSet;
public class HashSetToArray {
public static void main(String[] args) {
// Step 1: Create and populate a HashSet with elements
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Convert the HashSet to an array using the toArray method
String[] array = fruits.toArray(new String[0]);
// Step 3: Print the elements of the array
System.out.println("Array elements: ");
for (String fruit : array) {
System.out.println(fruit);
}
}
}
Output:
Array elements: Apple Banana Cherry
4. Step By Step Explanation
Step 1: We initialize a HashSet named fruits and add some elements to it.
Step 2: The toArray method is used to convert the HashSet to an array. It returns an array containing all of the elements in this set.
Step 3: The elements of the resulting array are printed, verifying that the HashSet has been successfully converted to an array.