Write a Java program to append the specified element to the end of a hash set


The program begins with the import statement import java.util.HashSet; , which imports the HashSet class from the java.util package. HashSet is a collection class in Java that implements the Set interface and stores unique elements.

Next, the program defines a public class called Append_Element. Within the Append_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, the program adds several elements to the HashSet using the add() method. The elements added are "C", "JAVA", "CPP", "PYTHON", "MYSQL", and "RUBY". Since HashSet stores only unique elements, any duplicates will be automatically removed.

Finally, 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.

Source Code

import java.util.HashSet;
public class Append_Element
{
	public static void main(String[] args)
	{
		HashSet<String> h_set = new HashSet<String>();
		h_set.add("C");
		h_set.add("JAVA");
		h_set.add("CPP");
		h_set.add("PYTHON");
		h_set.add("MYSQL");
		h_set.add("RUBY");
		System.out.println("Given HashSet : " + h_set);
	}
}

Output

Given HashSet : [JAVA, CPP, C, MYSQL, RUBY, PYTHON]

Example Programs