HashMap Constructors & Init
new HashMap() (default load 0.75), new HashMap(capacity) (avoids rehashing for large maps), new HashMap(otherMap) (copy constructor). Patterns for bulk-initializing from arrays and lists.
If I know roughly how many entries are coming, I size the map up front so it does not rehash repeatedly while filling.
How It Works
HashMap offers three constructors worth knowing: new HashMap() starts with capacity 16 and load factor 0.75, new HashMap(initialCapacity) pre-sizes the bucket array, and new HashMap(otherMap) shallow-copies an existing map. The load factor governs resizing, once entries exceed capacity × 0.75, the map doubles its bucket array and rehashes every entry, an O(n) event amortized across inserts.
When the eventual size is known, pre-sizing with roughly expectedSize / 0.75 elements avoids repeated rehashing during bulk loads. Bulk initialization typically pairs a constructor with a loop over an array or list, or with Map.of(...) for small immutable literals; the copy constructor is the quick way to snapshot a map before mutating it.
Step-by-Step Visualization
Code
Tips & Gotchas
Practice Problems
- 1Design HashMap
- 2Two Sum
- 3Group Anagrams
- 4Clone Graph
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
Does pre-sizing a HashMap actually matter for performance?
For large maps, yes. Growing from the default 16 buckets to a million entries triggers a series of doubling-and-rehash passes, each touching every stored entry. Constructing with the expected capacity up front, divided by the 0.75 load factor, eliminates all of them.
Is new HashMap(otherMap) a deep copy?
No. It copies the entries, but keys and values are the same object references as in the original. Mutating a shared value object is visible through both maps, so deep-copy the values yourself when true isolation is needed.