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

When Rehashing Occurs: The Threshold Calculation

Understand how HashMap calculates the rehash threshold (capacity × load factor) and triggers resizing.

When Rehashing Occurs: The Threshold Calculation

You'll learn exactly how HashMap decides when to trigger a resize by calculating the rehash threshold.

The Core Idea

HashMap doesn't wait until every bucket is filled before resizing. Instead, it uses a simple formula to calculate a threshold value. When the number of entries (size) exceeds this threshold, rehashing occurs. The formula is:

threshold = capacity × load factor

This calculation happens whenever the HashMap is created or resized.

How It Works in Practice

Let's say you create a HashMap with the default settings:

  • Initial capacity: 16 buckets
  • Load factor: 0.75

The threshold is calculated as: 16 × 0.75 = 12

This means that when you add the 13th element, the HashMap will trigger a rehash and resize to a larger capacity (typically doubling to 32 buckets). The new threshold then becomes 32 × 0.75 = 24.

Why This Matters

Think of the threshold as a "warning line" on a container. You don't want to fill a bucket completely to the brim because it becomes hard to manage. The load factor of 0.75 means "start worrying when you're 75% full," giving the HashMap room to maintain good performance before collisions become too common.

The threshold calculation ensures resize operations happen predictably based on the number of entries, not randomly or only when performance degrades severely.

Key Takeaway: HashMap calculates threshold = capacity × load factor to determine exactly when to trigger rehashing, typically resizing before the internal array becomes too crowded.