Java.Core.Explain the meaning of the parameters in the HashMap(int initialCapacity, float loadFactor) constructor.

💡 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:

SituationWhat to do
You know you’ll store ~1000 itemsUse initialCapacity = 1024 to avoid early resizes
Memory is tightUse a higher load factor (e.g. 0.9f)
Speed is criticalUse a lower load factor (e.g. 0.5f) for fewer collisions

🧠 TL;DR

ParameterMeaningDefault
initialCapacityHow many buckets (rounded to power of 2)16
loadFactorWhen to resize (size > capacity × loadFactor)0.75f
This entry was posted in Без рубрики. Bookmark the permalink.