Java HashSet add() Method (original) (raw)

Last Updated : 20 Jan, 2025

The HashSet **add() method in Java is used to add a specific element to the set. This method will add the element only if the specified element is not present in the HashSet. If the element already exists, the method will not add it again. This method ensures that no duplicate elements are added to the set.

**Example 1: This example demonstrates **how to add elements to a HashSet.

Java `

// Java program to demonstrates the // working of add() in HashSet import java.util.*; public class Geeks {

public static void main(String[] args)
{
    // Create HashSet
    HashSet<Integer> hs = new HashSet<Integer>();

    // Add elements to set
    hs.add(1);
    hs.add(2);
    hs.add(3);

    // Checking elements in HashSet
    System.out.println("HashSet: " + hs);
}

}

`

Syntax of HashSet add() Method

boolean add(E e)

**Example 2: This example demonstrates that **HashSet does not allow duplicate elements.

Java `

// Java program to demonstrate add() returning false // when trying to add a duplicate import java.util.HashSet;

public class Geeks { public static void main(String[] args) { // Create a HashSet HashSet hs = new HashSet<>();

    // Add elements to the HashSet
    System.out.println(hs.add("Java"));
    System.out.println(hs.add("C++"));

    // Trying to add a duplicate element
    System.out.println(hs.add("Java"));

    System.out.println("HashSet: " + hs);

    // Adding C
    System.out.println(hs.add("C"));

    // Trying to add a duplicate 
    // element again
    System.out.println(hs.add("C"));

    System.out.println("HashSet: " + hs);
}

}

`

Output

true true false HashSet: [Java, C++] true false HashSet: [Java, C++, C]