The
LinkedHashSet
is similar to theHashSet
, except thatLinkedHashSet
maintains the insertion order of elements, whereasHashSet
does not. Read more aboutLinkedHashSet
here.
The add
method adds an element to the LinkedHashSet
object if the element is not already present.
public boolean add(E e)
This method takes the element to be added to the set
as an argument.
The add
method returns true
if the passed element is not already present in the set
. Otherwise, the method returns false
.
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);}}
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
.