Write a Java program to Adding duplicate elements to HashSet


The program starts with the import statement import java.util.HashSet; , which imports the HashSet class from the java.util package.Next, the program defines a public class called Removing_Element. Within the Removing_Element 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 h_set = new HashSet();. The 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", "Yellow", 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 adds two duplicate elements, "Yellow" and "Blue", to the HashSet using the add() method. Note that HashSet does not allow duplicate elements, so these duplicates will not be added to the HashSet. HashSet will only store unique elements.

Finally, the program prints the updated contents of the HashSet using another System.out.println() statement. It displays the message "Display HashSet Elements: " followed by the elements in the HashSet, which includes the original elements and excludes the duplicates.

Source Code

import java.util.HashSet;
public class Removing_Element
{
	public static void main(String args[])
	{
		HashSet <String> h_set= new HashSet <String>();
		h_set.add("Blue");
		h_set.add("Green");
		h_set.add("Black");
		h_set.add("Orange");
		h_set.add("White");
		h_set.add("Yellow");
		h_set.add("Pink");
		System.out.println("Given HashSet : " + h_set);
		//Addition of duplicate elements in HashSet 
		h_set.add("Yellow");
		h_set.add("Blue");
 
		System.out.println("Display HashSet Elements : "+h_set);
	}
}

Output

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

Example Programs