💡 The constructor:
new HashMap(int initialCapacity, float loadFactor)
is one of the most powerful and fine-tuned ways to create a HashMap
. Let’s break down what each parameter means:
🧱 initialCapacity
This is the initial number of buckets (Node[]
array size) that the HashMap
will internally allocate before any resizing occurs.
- It is not the number of entries you can safely store — because of the
loadFactor
. - Internally, the capacity is rounded up to the next power of two (e.g., 10 → 16).
✅ Example:
new HashMap<>(10, 0.75f);
→ Actual internal capacity becomes 16.
⚖️ loadFactor
This is the threshold ratio for triggering rehashing (resizing).
Formula:
resizeThreshold = capacity × loadFactor
- When the number of entries exceeds this threshold, the map resizes (usually doubles the capacity).
- Default value is 0.75f, which balances space vs time:
- Good performance (fewer collisions),
- Efficient memory usage.
✅ Example:
new HashMap<>(16, 0.75f);
→ Resize will occur when more than 12 elements are added (16 × 0.75 = 12
).
🔥 Why you might customize these:
Situation | What to do |
---|---|
You know you’ll store ~1000 items | Use initialCapacity = 1024 to avoid early resizes |
Memory is tight | Use a higher load factor (e.g. 0.9f) |
Speed is critical | Use a lower load factor (e.g. 0.5f) for fewer collisions |
🧠 TL;DR
Parameter | Meaning | Default |
---|---|---|
initialCapacity | How many buckets (rounded to power of 2) | 16 |
loadFactor | When to resize (size > capacity × loadFactor ) | 0.75f |