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
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
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.
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); } }
Given HashSet : [White, Pink, Blue, Black, Orange, Green] HashSet Elements : [White, Pink, Blue, Yellow, Purple, Black, Orange, Green]
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions