If you are delving into Java programming and looking to understand collections, you will inevitably come across the HashSet class. Part of Java’s java.util
package, HashSet provides a way to store unique elements in an unordered manner.
Suggested Read: Java Collections Framework
In this blog, we will explore the key features, advantages, and practical usage of HashSet in Java.
What is a HashSet in Java?
A HashSet
is a collection that implements Set
interface, and its backing is a HashMap. Its size is limited, and elements are stored in a hash table so that no duplicates are allowed. This class is a part of the Java Collections Framework and is widely used for those cases when you want to keep unique elements.
Suggested Read: What is an Interface in Java?
Key Features of HashSet
- No Duplicate Elements: A HashSet automatically eliminates duplicate elements.
- Unordered Collection: The elements in a HashSet are not stored in any particular order.
- Allows Null Value: HashSet can store a single null value.
- Efficient Performance: Due to its hash table structure, HashSet provides average constant-time performance for basic operations like add, remove, and contains.
How Does a HashSet Work Internally?
HashSet internally stores elements in a HashMap . If an element is added, the hashCode()
method calculates it’s hash and if it has already been added, the equals()
method will ensure the duplicate value isn’t inserted. This mechanism gives HashSet its special storage behaviour.
Suggested Read: Hashmap in Java
Creating a HashSet in Java
Here’s a simple example to demonstrate how to create and use a HashSet:
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");
// Adding a duplicate element
fruits.add("Apple");
// Displaying the HashSet
System.out.println("Fruits: " + fruits);
// Checking if an element exists
System.out.println("Contains Banana? " + fruits.contains("Banana"));
// Removing an element
fruits.remove("Orange");
System.out.println("After Removal: " + fruits);
}
}
Output:
Fruits: [Banana, Orange, Apple]
Contains Banana? true
After Removal: [Banana, Apple]
Methods in HashSet
Here are some commonly used methods in the HashSet
class:
- add(E e): If the specified element is not already present in the set, it is added.
- remove(Object o): Removes the specified element from the set.
- contains(Object o): It Returns true if the specified element is contained in the set.
- size(): Returns the number of elements in the set.
- clear(): Removes all the elements from the set.
- isEmpty(): Checks if the set is empty.
- iterator(): It returns an iterator that goes over the elements in the set.
Advantages of HashSet
- Fast Performance: The hash based storage provides us add, remove, and search operations very efficiently.
- No Duplicates: Ensures unique elements in the collection.
- Null Support: Can store a single null value.
Limitations of HashSet
- Unordered Elements: The lack of order can be a drawback when ordering is required.
- Non-Synchronized: HashSet is not thread-safe; use
Collections.synchronizedSet()
for synchronized access.
Suggested Read: Synchronization in Java
When to Use HashSet
- When you need to store unique elements.
- When the order of elements does not matter.
- When performance is critical for add, remove, or lookup operations.
HashSet vs Other Sets
Feature | HashSet | LinkedHashSet | TreeSet |
---|---|---|---|
Order | Unordered | Insertion Order | Sorted Order |
Performance | High | Moderate | Low |
Null Support | Yes (1 null) | Yes (1 null) | No |
Synchronization | No | No | No |
Suggested Read: Difference between HashMap and HashTable
Conclusion
HashSet in Java is a powerful tool for managing collections of unique elements. Its simplicity and performance make it a go-to choice in many programming scenarios. While it has its limitations, understanding its internal workings and use cases can help you leverage its full potential.
Mastering HashSet and other Java collections is an essential step for any Java developer. Start incorporating HashSet in your projects to make your code more efficient and organized.
If you wish to learn more about Java enrol in our Free Java Programming Course and upskill today.
Frequently Asked Questions (FAQ’s)
1. Can a HashSet store duplicate elements?
No, a HashSet automatically eliminates duplicate elements by design.
2. Is HashSet thread-safe?
No, HashSet is not synchronized. For thread-safe operations, use Collections.synchronizedSet()
or ConcurrentHashMap
.
3. What happens if I add a null value to a HashSet?
A HashSet can store one null value, but multiple null values are not allowed.
4. How does HashSet differ from ArrayList?
HashSet is used for unique, unordered elements, while ArrayList allows duplicates and maintains order.
5. Can I sort elements in a HashSet?
No, HashSet does not maintain order. For sorted collections, consider using TreeSet instead.