HashSet Core Methods
add, remove, contains (all O(1)), size, isEmpty. Constructors: new HashSet<>(list), new HashSet<>(otherSet), new HashSet<>(Arrays.asList(...)). Set ops: addAll (union), retainAll (intersection), removeAll (difference). Convert back: new ArrayList<>(set).
I only need membership, not an associated value, so a set. contains at O(1) average is what collapses a nested loop into one pass.
How It Works
HashSet stores unique elements with O(1) average add, remove, and contains. Internally it is a HashMap using elements as keys. add returns false instead of inserting a duplicate, which doubles as a free duplicate detector. Common constructors include new HashSet<>(list) to deduplicate a collection in one step, and new HashSet<>(Arrays.asList(...)) for literals.
The bulk operations implement set algebra in place: addAll is union, retainAll is intersection, and removeAll is difference; convert back with new ArrayList<>(set) when list operations are needed afterward. Membership testing at O(1) is what turns quadratic scans into linear passes, as in Longest Consecutive Sequence, where the set answers 'does num - 1 exist?' instantly.
Step-by-Step Visualization
Code
Tips & Gotchas
Practice Problems
- 1Contains Duplicate
- 2Longest Consecutive Sequence
- 3Intersection of Two Arrays
- 4Happy Number
- 5Single Number
About the HashMap & HashSet API Pattern
The complete Java API for HashMap and HashSet. Constructors, every core method, iteration patterns, and set-based conversions. These are your building blocks for every hash-based problem.
If brute force is O(n²) because of a nested search, a hash map usually drops it to O(n). The tradeoff is O(n) extra space.
Common Hash Map Interview Problems
- Two Sum
- Subarray Sum Equals K
- Top K Frequent Elements
- LRU Cache
- Group Anagrams
- Longest Consecutive Sequence
Frequently Asked Questions
When should I choose a HashSet instead of a HashMap?
Use a set when you only care about membership. 'have I seen this before?', and a map when each element carries associated data such as a count or index. If you find yourself mapping every key to a dummy value like true, a set is the cleaner choice.
Do retainAll and removeAll modify the set in place?
Yes, both mutate the receiver: retainAll keeps only elements present in the argument (intersection) and removeAll deletes them (difference). Copy the set first with new HashSet<>(original) if the original contents are still needed.
Why does my HashSet of custom objects contain duplicates?
Uniqueness relies on equals and hashCode being consistently overridden; the defaults compare object identity, so two logically equal objects hash differently. Override both together (equal objects must produce equal hash codes) or the set cannot deduplicate them.