Skip to main content
HashMap & HashSet API

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.

O(n) for copy/bulk init
·
O(n)

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

new HashMap<>() — capacity 16, load factor 0.75. Rehashes at 12 entries
default
0
capacity
1
copy
2
from-set
3
freq
4
invert
5
group
6
Initial cap16
Rehash at12 entries
1/4

Code

Java
// ─── Constructors ────────────────────────────────────────────
Map<String, Integer> m1 = new HashMap<>();           // default cap 16
Map<String, Integer> m2 = new HashMap<>(64);         // hint capacity (avoids rehash)
Map<String, Integer> m3 = new HashMap<>(otherMap);   // copy constructor (shallow)

// ─── Build from data ──────────────────────────────────────────
// Frequency map from array
Map<Integer, Integer> freq = new HashMap<>();
for (int n : nums) freq.merge(n, 1, Integer::sum);

// Invert a map (value → key)
Map<Integer, String> inv = new HashMap<>();
original.forEach((k, v) -> inv.put(v, k));

// ─── Group: Map<K, List<V>> ───────────────────────────────────
Map<Integer, List<String>> grouped = new HashMap<>();
for (String s : words)
  grouped.computeIfAbsent(s.length(), k -> new ArrayList<>()).add(s);

// ─── From Set of keys ─────────────────────────────────────────
Set<String> keys = Set.of("a", "b", "c");
keys.forEach(k -> m1.put(k, 0));  // init all values to 0

Tips & Gotchas

1Default HashMap has initial capacity 16 and load factor 0.75
2Pass capacity hint to avoid rehashing: new HashMap<>(expectedSize * 2)
3Copy constructor new HashMap<>(other) is a shallow copy
4To invert a map, use entrySet() + a new map

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.

Key insight

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.