What is the LinkedHashSet.add method in Java?

The LinkedHashSet is similar to the HashSet, except that LinkedHashSet maintains the insertion order of elements, whereas HashSet does not. Read more about LinkedHashSet here.

The add method adds an element to the LinkedHashSet object if the element is not already present.

Syntax

public boolean add(E e)

Parameters

This method takes the element to be added to the set as an argument.

Return value

The add method returns true if the passed element is not already present in the set. Otherwise, the method returns false.

Code

import java.util.LinkedHashSet;
class Add {
public static void main( String args[] ) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(1);
set.add(2);
set.add(3);
System.out.println("Calling set.add(3). Is added - " + set.add(3));
System.out.println("Calling set.add(4). Is added - " + set.add(4));
System.out.println("The set is " + set);
}
}

Explanation

In the code above, we:

  • In line 1: Import the LinkedHashSet class.

  • In line 4: Create a new LinkedHashSet object with the name set.

  • From lines 5 to 7: Use the add method to add three elements (1,2,3) to the set object.

  • In line 10: Use the add method to add element 3 to the set. The element 3 is already present in the set, so the set remains unchanged and the method returns false.

  • In line 11: Use the add method to add element 4 to the set. The element 4 is not present in the set, so the element is added to the set and the method returns true.

Free Resources