Course contentsShow
← Java
Lesson 1123 of 2,87026. Map ImplementationsFree lesson

Understanding Load Factor: Capacity vs Size

Learn what load factor means in HashMap: the ratio of entries to buckets, and why it matters for performance.

Understanding Load Factor: Capacity vs Size

You'll learn what load factor actually measures in a HashMap and how it relates to the number of entries and available buckets.

Capacity, Size, and the Load Factor Formula

When working with HashMap, it's crucial to understand three related but distinct values:

  • Capacity: The total number of buckets in the internal array
  • Size: The number of actual key-value entries stored in the map
  • Load Factor: The ratio size / capacity

Think of a HashMap like a parking lot. Capacity is the total number of parking spaces. Size is how many cars are currently parked. Load factor is the percentage of spaces occupied.

Why This Ratio Matters for Performance

The load factor determines how "crowded" your HashMap is. When the load factor reaches the configured threshold (typically 0.75), the HashMap triggers rehashing to create more buckets.

For example:

  • Capacity: 16 buckets
  • Size: 12 entries
  • Current load factor: 12/16 = 0.75

At this point, if you add one more entry (size becomes 13), the load factor would exceed 0.75, triggering rehashing to double the capacity to 32 buckets.

The Performance Connection

A lower load factor means more empty buckets, which reduces collision chains and maintains O(1) performance. However, it wastes memory.

A higher load factor means more entries per bucket on average, leading to longer collision chains (or more tree bins) but using memory more efficiently.

The default 0.75 strikes a balance: HashMap stays performant while not wasting too much space on empty buckets.

Key Takeaway: Load factor is the ratio of entries to buckets (size/capacity) that determines when HashMap needs to grow; it directly impacts the trade-off between speed and memory usage.