Last Updated : 11 Jul, 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);
}
}
HashSet: [1, 2, 3]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<String> 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);
}
}
true true false HashSet: [Java, C++] true false HashSet: [Java, C++, C]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4