Java HashSet add(E e) Example

In this tutorial we will learn about add(E e) method of java.util.HashSet class. This method inserts the specified element to the end of the HashSet

Signature

public boolean add(E e)

This method appends the specified element to the end of this HashSet.e is the element which will be appended and will return true on successful insertion.

Example

The following example shows the usage of java.util.HashSet.add(e) method.

import java.util.HashSet;

public class AddMethodHashSetExample 
{
	public static void main(String args[])
	{
		// Create HashSet hashset1 object
		HashSet hashset1 = new HashSet();
		
		//adding elements to hashset1 using add()
		hashset1.add("Element1");
		hashset1.add("Element2");
		hashset1.add("Element3");
		boolean flag = hashset1.add("Element4");
		
		System.out.println("Is the insertion successful ??"+flag);
		
		//Printing the elements of the HashSet
		System.out.println("**Elements of the HashSet**");
		for(String val : hashset1)
		{
			System.out.println(val);
		}
	}
}

Output

Is the insertion successful ??true
**Elements of the HashSet**
Element1
Element2
Element3
Element4

Leave a Reply

Your email address will not be published. Required fields are marked *