VOOZH about

URL: https://www.geeksforgeeks.org/java/hashset-add-method-in-java/

⇱ Java HashSet add() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java HashSet add() Method

Last Updated : 11 Jul, 2025

The HashSetadd() 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.


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.


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