Hash Set
Hash Set
1. What is HashSet?
HashSet is a part of the Java Collection Framework, under java.util package.
It implements the Set interface and does not allow duplicate elements.
It is unordered (does not maintain insertion order).
Uses a hash table for storing elements, offering constant-time performance (O(1))
for basic operations like add, remove, and contains.
2. Key Features of HashSet
No Duplicates – Only unique elements are stored.
Unordered Collection – Does not maintain insertion order.
Allows Null – Can store a single null value.
Not Thread-Safe – Use Collections.synchronizedSet() for thread safety.
Uses Hashing – Provides fast lookup and retrieval.
3. Example Program: Using HashSet in Java
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// Creating a HashSet
HashSet<String> fruits = new HashSet<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Grapes");
fruits.add("Banana"); // Duplicate, won't be added
// Displaying elements
System.out.println("HashSet elements: " + fruits);
// Removing an element
fruits.remove("Grapes");
System.out.println("After removing 'Grapes': " + fruits);
// Checking size
System.out.println("Size of HashSet: " + fruits.size());
Method Description