Java Utility Library

Java HashSet - add() Method



The java.util.HashSet.add() method is used to add a new element in the set. The element is added if it is not already present in the set.

Syntax

public boolean add(E element)

Here, E is the type of element maintained by the container.


Parameters

element Specify element which need to be added in the set.

Return Value

Returns true if the element is successfully added, else returns false.

Exception

NA

Example:

In the example below, the java.util.HashSet.add() method is used to add new element in the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating hash set
    HashSet<Integer> MySet = new HashSet<Integer>();

    //populating hash set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    //printing hash set
    System.out.println("MySet contains: " + MySet);   
  }
}

The output of the above code will be:

MySet contains: [20, 40, 10, 30]

❮ Java.util - HashSet