Java LinkedHashSet add(E e) Method Example

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

Signature

public boolean add(E e)

This method appends the specified element to the end of this LinkedHashSet.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.LinkedHashSet.add(e) method.

import java.util.LinkedHashSet;

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

Output

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

Leave a Reply

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