
HashSet in Java
Introduction
HashSet in Java, HashSet in Java is a powerful data structure that stores a collection of unique elements, ensuring that no duplicates are allowed. It is a part of the Java Collections Framework and is widely used for tasks where uniqueness matters and fast lookups are needed. Behind the scenes, HashSet is backed by a HashMap, using a technique called hashing to store elements efficiently. Unlike lists or arrays where elements are ordered and can be duplicated, HashSet does not maintain any order of elements and automatically ignores duplicate insertions. It can store one null
value, and operations like adding, removing, and searching are generally performed in constant time. Overall, HashSet is ideal when you need to maintain a collection of distinct elements with quick access and no concern for order.
List of Content
- What is HashSet?
- Why Use HashSet?
- Key Features of HashSet
- How HashSet Works Internally
- Creating and Initializing a HashSet
- Common Operations in HashSet
- Important Methods in HashSet
- Null Values in HashSet
- Iterating Through a HashSet
- HashSet vs Other Set Implementations (LinkedHashSet, TreeSet)
- Conclusion
π What is HashSet?
A HashSet
in Java is a collection that stores only unique elements and does not allow duplicates. It is part of the Java Collections Framework and implements the Set interface. Internally, it is backed by a HashMap, which uses hashing to store elements efficiently. Unlike lists or arrays, a HashSet
does not maintain any order of elements. It allows storing one null value and provides constant-time performance for most basic operations like adding, removing, and checking if an element exists.
π€ Why Use HashMap?
- No duplicates β Automatically ignores duplicate insertions.
- Fast operations β Adding, removing, and searching are generally
O(1)
. - Best for membership tests β Quickly check if an element exists.
- Lightweight β Does not store extra indexing information.
π Key Features of HashSet:
- Stores unique elements only.
- Does not guarantee order of elements.
- Backed by a HashMap internally.
- Allows one null value.
- Not thread-safe (needs synchronization for multi-threading).
- Offers constant-time complexity for most basic operations.
βοΈ How HashSet Works Internally:
- When an element is added, its hashCode is calculated.
- Based on the hash code, the element is stored in a corresponding bucket of the internal HashMap.
- If another element with the same hash code is added,
equals()
is used to check for equality. - If equal, it is ignored (duplicate). If not equal, it is stored in the same bucket but still remains unique.
π Creating ans Initializing a HashSet:
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("Mango");
System.out.println(fruits);
}
}
π Comman Operations in HashSet:
fruits.add("Orange"); // Add element
fruits.remove("Banana"); // Remove element
fruits.contains("Apple"); // Check if exists
fruits.size(); // Get total elements
fruits.clear(); // Remove all elements
π Important methods in HashSet:
add(E element)
β Adds an element.remove(Object o)
β Removes an element if present.contains(Object o)
β Checks if element exists.isEmpty()
β Checks if set is empty.size()
β Returns total elements.clear()
β Removes all elements.
π‘ Null Values in HashSet:
- HashSet allows only one null value.
- If you try adding
null
multiple times, it will still store just one.
Let's Take an Example with dry run:
import java.util.*;
public class HashSetMethodsDemo {
public static void main(String[] args) {
// CREATE A HASHSET
HashSet<String> set = new HashSet<>();
// add() - ADD ELEMENTS
set.add("Apple");
set.add("Banana");
set.add("Mango");
set.add("Orange");
set.add("Apple"); // DUPLICATE, WILL BE IGNORED
// DISPLAY THE SET
System.out.println("HashSet: " + set);
// contains() - CHECK IF ELEMENT EXISTS
System.out.println("Contains 'Banana'? " + set.contains("Banana")); // TRUE
// remove() - REMOVE AN ELEMENT
set.remove("Mango");
System.out.println("After removing 'Mango': " + set);
// size() - GET TOTAL ELEMENTS
System.out.println("Size of HashSet: " + set.size());
// isEmpty() - CHECK IF EMPTY
System.out.println("Is HashSet empty? " + set.isEmpty());
// ITERATING USING FOR-EACH LOOP
System.out.println("Iterating using for-each loop:");
for (String fruit : set) {
System.out.println(fruit);
}
// ITERATING USING ITERATOR
System.out.println("Iterating using Iterator:");
Iterator<String> it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// clear() - REMOVE ALL ELEMENTS
set.clear();
System.out.println("After clearing: " + set);
}
}
INITIAL STATE
set
is created β[]
(empty HashSet)
STEP 1: ADD ELEMENTS:
set.add("Apple");
- Adds
"Apple"
β["Apple"]
set.add("Banana");
- Adds
"Banana"
β["Apple", "Banana"]
set.add("Mango");
- Adds
"Mango"
β["Apple", "Banana", "Mango"]
set.add("Orange");
- Adds
"Orange"
β["Apple", "Banana", "Mango", "Orange"]
set.add("Apple"); // Duplicate
"Apple"
already exists β Ignored- HashSet does not allow duplicates.
Current set:["Apple", "Banana", "Mango", "Orange"]
(Order may vary because HashSet is unordered.)
STEP 2: CHECK CONTAINS:
set.contains("Banana");
"Banana"
is present β returnstrue
.
STEP 3: REMOVE ELEMENT:
set.remove("Mango");
- Removes
"Mango"
β["Apple", "Banana", "Orange"]
STEP 4: SIZE:
set.size();
- Current size β
3
.
STEP 5: CHECK EMPTY:
set.isEmpty();
- Set has elements β returns
false
.
STEP 6: CLEAR ALL ELEMENTS:
set.clear();
- Set becomes empty β
[]
.
π Iterating Through HashMap:
for (String fruit : fruits) {
System.out.println(fruit);
}
// OR using Iterator
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
π HashSet vs Other Set Implementations:
Feature | HashSet | LinkedHashSet | TreeSet |
---|---|---|---|
Order maintained | No | Yes (Insertion order) | Yes (Sorted order) |
Performance (O) | O(1) | O(1) | O(log n) |
Allows null value | Yes (one) | Yes (one) | No |
Backed by | HashMap | LinkedHashMap | TreeMap |
β CONCLUSION:
HashSet
is a great choice when you need a collection of unique elements with fast access and no concern for order. Itβs lightweight, efficient, and perfect for scenarios like removing duplicates, membership checks, and building sets of data without extra overhead.
Happy Learning! π
π For more blogs and topics, Click Here.
4 Reactions
0 Bookmarks