Open In App

Java HashSet add() Method

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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);
    }
}

Output
HashSet: [1, 2, 3]

Syntax of HashSet add() Method

boolean add(E e)

  • Parameter: The element to be added to the HashSet.
  • Return Type: This method returns "true" if the element was not present in the set and was successfully added, otherwise returns "false" if the element already exists in the set.

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);
    }
}

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

Next Article

Similar Reads