How to Add Element to HashSet in Java: Simple Guide
To add an element to a
HashSet in Java, use the add() method. For example, hashSet.add(element); adds the element if it is not already present.Syntax
The basic syntax to add an element to a HashSet is:
hashSet.add(element);
Here, hashSet is your HashSet object, and element is the item you want to add.
The add() method returns true if the element was added successfully (it was not already in the set), or false if the element was already present.
java
HashSet<Type> hashSet = new HashSet<>(); hashSet.add(element);
Example
This example shows how to create a HashSet of strings and add elements to it. It also prints the set to show the added elements.
java
import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<String> fruits = new HashSet<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Trying to add a duplicate element boolean added = fruits.add("Apple"); System.out.println("Added Apple again? " + added); System.out.println("Fruits in the set: " + fruits); } }
Output
Added Apple again? false
Fruits in the set: [Apple, Banana, Cherry]
Common Pitfalls
Some common mistakes when adding elements to a HashSet include:
- Trying to add
nullelements when not expected (allowed but can cause issues if not handled). - Expecting
add()to add duplicates —HashSetdoes not allow duplicates, so duplicates are ignored. - Not importing
java.util.HashSetwhich causes compilation errors.
Example of wrong and right usage:
java
import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<String> set = new HashSet<>(); // Wrong: expecting duplicates to be added set.add("Java"); set.add("Java"); System.out.println(set.size()); // Output: 1, not 2 // Right: check if add returns false for duplicates boolean added = set.add("Java"); System.out.println("Added duplicate? " + added); // false } }
Output
1
Added duplicate? false
Quick Reference
Here is a quick summary of adding elements to a HashSet:
| Action | Description |
|---|---|
hashSet.add(element); | Adds element if not present, returns true if added |
hashSet.add(null); | Adds null element (allowed once) |
hashSet.add(duplicate); | Does not add duplicate, returns false |
import java.util.HashSet; | Required import for using HashSet |
Key Takeaways
Use the add() method to add elements to a HashSet in Java.
HashSet does not allow duplicate elements; add() returns false if element exists.
You can add null once to a HashSet, but be cautious when using null.
Always import java.util.HashSet before using it.
Check the boolean result of add() to know if the element was actually added.