1. Introduction
In Java, arrays are used to store multiple values of the same type. However, arrays do not offer the dynamic features that collections do. If you have an array and want to leverage the features provided by the HashSet class in the Java Collections Framework, such as avoiding duplicate elements and not maintaining any order, you can convert the array to a HashSet.
2. Program Steps
1. Initialize an array with elements.
2. Convert the array to a HashSet using the Arrays.asList method followed by passing it to the HashSet constructor.
3. Print the elements of the HashSet.
3. Code Program
import java.util.Arrays;
import java.util.HashSet;
public class ArrayToHashSet {
public static void main(String[] args) {
// Step 1: Initialize an array with elements
String[] array = {"Apple", "Banana", "Cherry", "Apple"};
// Step 2: Convert the array to a HashSet using the Arrays.asList method followed by passing it to the HashSet constructor
HashSet<String> fruits = new HashSet<>(Arrays.asList(array));
// Step 3: Print the elements of the HashSet
System.out.println("HashSet elements: " + fruits);
}
}
Output:
HashSet elements: [Banana, Cherry, Apple]
4. Step By Step Explanation
Step 1: An array named array is initialized with some elements, including a duplicate "Apple".
Step 2: The Arrays.asList method is used to convert the array to a List, which is then passed to the HashSet constructor. This results in creating a HashSet named fruits with the elements from the array, removing any duplicates.
Step 3: The elements of the HashSet are printed, and we can observe that the duplicate "Apple" is removed.