Introduction
The Java HashSet class is one of the most commonly used implementations of the Set interface in the Java Collection Framework. It is designed to store unique elements, meaning it automatically prevents duplicate values from being added. If you attempt to insert the same element multiple times, the HashSet simply ignores the duplicate.
The HashSet class belongs to the java.util package and internally uses a HashMap to store its elements.
HashSet does not maintain insertion order and does not sort its elements. The order of elements may change over time and should not be relied upon.
What is Java HashSet?
A HashSet is a collection that stores unique elements using a hash table.
When an element is added:
- Java calculates its hash code.
- The element is placed into an internal bucket.
- If an equal element already exists, the duplicate is ignored.
Example:
Input:
Java
Python
Java
Spring
Python
Output:
Python
Spring
The duplicate values are automatically removed.
Key Characteristics
- Stores unique elements only
- Does not maintain insertion order
- Does not sort elements
- Allows one null value
- Uses hashing for fast performance
- Dynamic size
- Not synchronized
- Supports Generics
Java HashSet Hierarchy
Object
│
AbstractCollection
│
AbstractSet
│
HashSet
The HashSet class implements:
- Set
- Collection
- Iterable
- Serializable
- Cloneable
Features of Java HashSet
Some important features include:
- Stores unique elements
- Fast insertion and lookup
- Dynamic resizing
- Allows one null element
- Does not preserve insertion order
- Backed internally by HashMap
- Supports Generics
- Excellent average-case performance
Syntax
Import Statement
import java.util.HashSet;
or
import java.util.*;
Creating a HashSet
HashSet<String> languages = new HashSet<>();
Using the Set interface:
Set<String> languages = new HashSet<>();
Programming to the Set interface is considered a best practice.
Constructors of HashSet
1. Default Constructor
HashSet<String> Set = new HashSet<>();
Creates an empty HashSet with the default capacity.
2. Constructor with Initial Capacity
HashSet<Integer> Number = new HashSet<>();
Creates a HashSet with an initial capacity of 20.
3. Constructor with Capacity and Load Factor
HashSet<Integer> Number = new HashSet<>(20,0,);
- Initial capacity = 20
- Load factor = 0.75
The load factor determines when the internal hash table should be resized.
4. Constructor from Another Collection
HList<String> list = Arrays.asList("Java", "Python", "Java");
HashSet<String> set = new HashSet<>(list);
System.out.println(set);
Output
Common Methods of HashSet
| Method | Description |
|---|---|
| addFirst() | Adds an element |
| remove() | Removes an element |
| contains() | Checks whether an element exists |
| size() | Returns the number of elements |
| isEmpty() | Checks whether the Set is empty |
| clear() | Removes all elements |
| iterator() | Returns an iterator for traversal |
| addAll() | Adds all elements from another collection |
| removeAll() | Removes matching elements |
| retainAll() | Keeps only common elements |
Example 1: Creating a HashSet
import java.util.*;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>(list);
courses.add("Java");
courses.add("Python");
courses.add("Spring Boot");
System.out.println(courses);
}
}
Output
The output order may vary because HashSet does not maintain insertion order.
Example 2: Removing Duplicate Elements
import java.util.*;
public class DuplicateExample {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>(list);
numbers.add(10);
numbers.add(20);
numbers.add(10);
numbers.add(30);
System.out.println(numbers);
}
}
Output
The duplicate value 10 is automatically ignored.
Example 3: Checking an Element
import java.util.*;
public class ContainsExample {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>(list);
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits.contains("Banana"));
}
}
Output
Example 4: Removing an Element
import java.util.*;
public class RemoveExample {
public static void main(String[] args) {
HashSet<String> cities = new HashSet<>(list);
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Jaipur");
cities.remove("Mumbai");
System.out.println(cities);
}
}
Output
Example 5: Iterating Through a HashSet
import java.util.*;
public class LoopExample {
public static void main(String[] args) {
HashSet<String> skills = new HashSet<>(list);
skills.add("Java");
skills.add("Spring");
skills.add("Hibernate");
for(String skill : skills){
System.out.println(skill);
}
}
}
Output
Spring
Hibernate
How HashSet Works Internally
Internally, a HashSet uses a HashMap.
The process of adding an element is:
- Java calculates the element’s hashCode().
- The hash code determines the bucket where the element will be stored.
- If the bucket is empty, the element is inserted.
- If another element already exists in the bucket, Java compares them using the equals() method.
- If both objects are equal, the new element is ignored; otherwise, it is stored.
This mechanism provides very fast average-case performance for add, remove, and contains operations.
HashSet vs LinkedHashSet vs TreeSet
| Feature | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
| Duplicate Elements | No | No | No |
| Insertion Order | No | Yes | No |
| Sorted Order | No | No | Yes |
| Allows Null | Yes (one) | Yes (one) | Yes |
| Internal Structure | Hash Table | Hash Table + Linked List | Red-Black Tree |
| Performance | Fastest | Fast | Slower |
Time Complexity
| Operation | Time Complexity |
|---|---|
| add() | O(1) (Average) |
| remove() | O(1) (Average) |
| contains() | O(1) (Average) |
| size() | O(1) |
| iteration | O(n) |
In rare cases involving many hash collisions, some operations may degrade, but under normal circumstances HashSet offers excellent performance.
Real-life Example
Imagine you’re building a website registration system.
Users register with their email addresses:
john@example.com
alice@example.com
john@example.com
Since duplicate email addresses should not be allowed, storing them in a HashSet ensures that each email appears only once.
Other real-world applications include:
- User registration systems
- Product ID storage
- Student roll numbers
- Employee ID management
- Removing duplicate records
- Search history
- Unique tags and categories
- Caching unique values
Limitations of Java HashSet
- Does not maintain insertion order
- Does not sort elements
- No index-based access
- Not synchronized
- Performance depends on a good implementation of hashCode() and equals() for custom objects
Common Mistakes
1. Expecting Ordered Output
Incorrect assumption:
HashSet<String> set = new HashSet<>(list);
set.add("A");
set.add("B");
set.add("C");
System.out.println(set);
The output order is not guaranteed.
2. Forgetting Generics
Incorrect:
HashSet set = new HashSet();
Correct:
HashSet<String> set = new HashSet<>(list);
3. Trying to Store Duplicate Values
set.add("Java");
set.add("Java");
Only one “Java” is stored.
4. Using get() Method
Incorrect:
set.get(0);
A HashSet does not support index-based access.
5. Ignoring equals() and hashCode() in Custom Objects
When storing custom objects in a HashSet, always override both equals() and hashCode(). Otherwise, duplicate detection may not work as expected.
Best Practices
- Program to the Set interface.
Set<String> users = new HashSet<>();
- Use HashSet when ordering is not required.
- Override equals() and hashCode() for custom objects.
- Use Generics for compile-time type safety.
- Choose LinkedHashSet if insertion order is important.
- Choose TreeSet if sorted elements are required.
Conclusion
The Java HashSet class is one of the fastest and most widely used implementations of the Set interface. By storing only unique elements and using a hash table internally, it provides excellent performance for adding, removing, and searching elements. Although it does not maintain insertion order or sort its contents, HashSet is an ideal choice when uniqueness and speed are the primary requirements.
Whether you’re removing duplicate records, managing unique user data, or building high-performance applications, HashSet is an essential collection class every Java developer should understand.