Let’s learn HashSet add(E e) method in java.
HashSet add(E e) method in java
add(E e) method of HashSet class adds the specified element to this set if it is not already present.
More formally, adds the specified element e to this set if this set contains no element e2 such that Objects.equals(e, e2).
If this set already contains the element, the call leaves the set unchanged and returns false.
Syntax:
public boolean add(E e)
Parameters:
e element to be added to this set.
Returns:
true if this set did not already contain the specified element.
Now let’s see example on HashSet add(E e) method.
import java.util.HashSet; public class HashSetAddMethodExample { public static void main(String[] args) { HashSet<String> hs = new HashSet<String>(); // populating hash set hs.add("violet"); hs.add("indigo"); hs.add("blue"); hs.add("green"); hs.add("yellow"); System.out.println("HashSet of colors: " + hs); } }
Output:
HashSet of colors: [green, blue, violet, yellow, indigo]
Reference – oracle docs
Also read – java overview