Write a Java program to Adding ArrayList elements to HashSet


The program starts with the import statement import java.util.*;, which imports all classes from the java.util package, including HashSet. Next, the program defines a public class called ArrayList_HashSet.

Within the ArrayList_HashSet class, the main method is declared and serves as the entry point for the program. It takes an array of strings (args) as input. Inside the main method, a new instance of the HashSet class is created using the constructor: HashSet arr = new HashSet();. The <String> 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 using the add() method. The elements added are "Blue", "Green", "Black", "Orange", "White", and "Pink". Next, the program prints the contents of the HashSet using the System.out.println() statement. It displays the message "Given HashSet: " followed by the elements contained in the HashSet.

The program then creates a new HashSet called h_set and initializes it with the elements of the original HashSet arr using the constructor: HashSet h_set = new HashSet(arr);. This is a way to copy the elements from one HashSet to another. After copying the elements, the program adds two additional elements, "Yellow" and "Purple", to the h_set HashSet using the add() method.

Finally, the program prints the contents of the h_set HashSet using another System.out.println() statement. It displays the message "HashSet Elements: " followed by the elements in the HashSet, which include the elements from the original HashSet arr as well as the two additional elements.

Source Code

import java.util.*;
public class ArrayList_HashSet
{
	public static void main(String args[])
	{
		HashSet <String> arr = new HashSet <String>();
		arr.add("Blue");
		arr.add("Green");
		arr.add("Black");
		arr.add("Orange");
		arr.add("White");
		arr.add("Pink");
		System.out.println("Given HashSet : " + arr);
 
		//copying ArrayList elements to HashSet
		HashSet<String> h_set =new HashSet(arr);
 
		//adding another element to HashSet after copy
		h_set.add("Yellow");
		h_set.add("Purple");
 
		System.out.println("HashSet Elements : "+h_set);
	}
}

Output

Given HashSet : [White, Pink, Blue, Black, Orange, Green]
HashSet Elements : [White, Pink, Blue, Yellow, Purple, Black, Orange, Green]

Example Programs