Course contentsShow
← Java
Lesson 1057 of 2,87025. Set ImplementationsFree lesson

What Is Load Factor in HashSet?

Learn how load factor determines when a HashSet's underlying HashMap grows to maintain performance.

What Is Load Factor in HashSet?

You'll learn how the load factor determines when a HashSet's underlying HashMap automatically expands to maintain fast performance.

The Core Idea

The load factor is a threshold that controls when the HashSet's internal HashMap grows. It's expressed as a decimal between 0 and 1, representing the ratio of "how full" the HashMap can get before it needs to resize.

The default load factor is 0.75, meaning when the HashMap reaches 75% capacity, it automatically doubles in size.

Why Load Factor Matters

Think of a HashSet like a parking garage with numbered spots. When too many cars fill the garage (high load), finding an empty spot takes longer because of collisions. The load factor is like setting a rule: "When the garage is 75% full, build a bigger garage and redistribute the cars."

Formula:

If (size > capacity × load_factor) → resize

For example, with initial capacity 16 and load factor 0.75:

  • Resize triggers when size exceeds 16 × 0.75 = 12 elements
  • After resize, capacity becomes 32
  • Next resize at 32 × 0.75 = 24 elements

The Trade-off

  • Lower load factor (e.g., 0.5): More memory used, fewer collisions, faster lookups
  • Higher load factor (e.g., 0.9): Less memory wasted, more collisions, slower lookups

The default 0.75 is a sweet spot balancing time and space efficiency.

When you create a HashSet, you can specify both initial capacity and load factor to optimize for your use case.

Key Takeaway:
The load factor (default 0.75) determines when HashSet's HashMap resizes—balancing memory usage against performance by triggering expansion before the hash table becomes too crowded with collisions.