Java HashSet
A HashSet in Java is a collection that contains no duplicate elements. It implements the Set interface and is backed by a hash table. HashSet makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
1. Creating a HashSet
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
}
}
2. Adding Elements
Use the add() method to add elements to the HashSet.
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicate element, will not be added
3. Iterating Over a HashSet
for (String item : set) {
System.out.println(item);
}
4. Common Methods
contains(Object o)- Checks if the set contains the specified element.remove(Object o)- Removes the specified element from the set.size()- Returns the number of elements.clear()- Removes all elements.
5. Key Takeaways
HashSetstores unique elements only (no duplicates).- Does not maintain any order of elements.
- Allows one null element.
- Not synchronized; external synchronization is required for thread safety.
- Use when you need to prevent duplicates and don't care about order.