Java HashSet
HashSet is one of the most commonly used implementations of the Set interface in Java. It belongs to the java.util
package and represents a collection that does not allow duplicate elements. It is backed by a hash table, making it highly efficient for operations like adding, removing, and checking the presence of elements.
Key Characteristics of HashSet#
- Implements Set Interface: Inherits all characteristics of Set such as no duplicates.
- Backed by HashMap: Internally uses a
HashMap
to store elements. - No Order Guarantee: Does not maintain the insertion order of elements.
- Allows One null Value: Can store a single
null
element. - Not Thread-safe: Needs external synchronization for concurrent access.
- Fast Performance: Provides constant-time performance for basic operations like add, remove, and contains (O(1) on average).
Constructors#
Commonly Used Methods in HashSet#
Method | Description |
---|---|
add(E e) | Adds the element to the set if not already present. |
addAll(Collection<? extends E> c) | Adds all elements from another collection. |
remove(Object o) | Removes the specified element. |
contains(Object o) | Checks if the set contains the element. |
isEmpty() | Returns true if the set is empty. |
size() | Returns the number of elements in the set. |
clear() | Removes all elements from the set. |
iterator() | Returns an iterator over the elements. |
Example: Basic Operations with HashSet#
Output:#
(Note: Output order may vary due to no guaranteed order in HashSet.)
Iterating over HashSet#
Output:#
(Order is not guaranteed)
Performance Analysis#
Operation | Time Complexity |
---|---|
add | O(1) average |
remove | O(1) average |
contains | O(1) average |
iteration | O(n) |
- Performance may degrade if many elements have the same hash code.
- Best suited for scenarios where quick lookup, insertion, or deletion is needed, and order does not matter.
When to Use HashSet#
- When you want to store unique values.
- When you don’t care about the order of elements.
- When you need high-performance operations (add, remove, contains).
Conclusion#
In this blog, we explored the HashSet
class in Java:
- It is a part of the Java Collection Framework and implements the
Set
interface. - HashSet ensures uniqueness and offers excellent performance due to its internal hashing mechanism.
- It is best used when the order of elements doesn't matter but fast access is needed.
In the next blog, we will dive into LinkedHashSet
and see how it maintains insertion order while still ensuring uniqueness.