Learn-dsa..in 30 days!



























HashSet Basics

Java Hashset is a collection of elements that can contain null elements but cannot contain duplicates. HashSet does not store or retrieve elements in the order that the same were added to the HashSet.

Use cases for HashSets

HashSets can be used for usecases where we need to remove duplicates.
HashSets can be used for use cases where we need to check containership of elements in the HashSet.
HashSets can be used for operations like set unions, intersections, disjunctions, filtering of data etc.

Advantages of HashSets

HashSets do not store duplicates, so these can be used to check for duplicates.
HashSets are not thread-safe so multiple threads can read /access the same concurrently.
HashSets are efficient for operations such as inserts, access and delete.

Disadvantages of HashSets

Elements are not sorted in HashSets.
HashSets underlying data structures (hashtable) consumes more memory.

Time Complexity of Java HashSet operations:

Following table shows time complexity metrics for HashSet operations:

Operation Complexity
Add operation. O(1)
Remove/Delete operation. O(1)
Contains/lookup operation. O(1)
Get size of HashSet. O(1)