What is the LinkedHashSet.add method in Java?
The
LinkedHashSetis similar to theHashSet, except thatLinkedHashSetmaintains the insertion order of elements, whereasHashSetdoes not. Read more aboutLinkedHashSethere.
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
LinkedHashSetclass. -
In line 4: Create a new
LinkedHashSetobject with the nameset. -
From lines 5 to 7: Use the
addmethod to add three elements (1,2,3) to thesetobject. -
In line 10: Use the
addmethod to add element3to theset. The element3is already present in theset, so thesetremains unchanged and the method returnsfalse. -
In line 11: Use the
addmethod to add element4to theset. The element4is not present in theset, so the element is added to thesetand the method returnstrue.