Skip to main content

Why HashMap Uses (n - 1) & hash and Why Capacity Is Always Power of 2

Why HashMap Uses (n - 1) & hash and Why Capacity Is Always Power of 2

If you are learning Java HashMap internals, one line that often confuses beginners is:

index = (n - 1) & hash;

Many people ask:

  • Where is the power of 2 here?

  • Why not use % (modulo)?

  • Why does HashMap care so much about powers of 2?

In this article, we’ll explain everything in very simple terms.


What Is n in (n - 1) & hash?

In this formula:

index = (n - 1) & hash;

n is the capacity of the HashMap, meaning the number of buckets.

Important rule:

HashMap capacity is ALWAYS a power of 2

Examples:

  • 16 → 2⁴

  • 32 → 2⁵

  • 64 → 2⁶

  • 128 → 2⁷

So the power of 2 is hidden inside n.


Why HashMap Capacity Must Be Power of 2

HashMap calculates bucket index using bitwise AND (&), not modulo (%).

This works correctly only when n is a power of 2.

Let’s understand this with an example.


Example: Capacity = 16 (Power of 2)

Binary values:

n     = 16  → 10000
n - 1 = 15  → 01111

Now suppose the hash value is:

hash = 10110101

Apply bitwise AND:

  10110101
& 01111
-----------
  00101  → index = 5

What happened here?

  • (n - 1) created a bitmask

  • The bitmask ensures the index is always between 0 and 15

  • Every bucket gets a fair chance to be used

This is fast and efficient.


What If Capacity Is NOT Power of 2? (Important Interview Trap)

Suppose:

n = 10
n - 1 = 9 → 1001

Now:

hash = 10110101
& 1001
-------
 1001 → index = 9

Problems:

  • Many bucket indexes are never used

  • Keys cluster in fewer buckets

  • Collisions increase

  • Performance degrades

That’s why HashMap never allows non-power-of-2 capacity internally.


Why HashMap Does NOT Use % (Modulo)

You may wonder:

index = hash % n;

Why not use this?

Reasons HashMap avoids modulo:

  1. % is slower than bitwise operations

  2. & is much faster at CPU level

  3. Power-of-2 capacity makes modulo unnecessary

  4. Better performance under heavy load

Interview answer:

HashMap avoids modulo and uses bitwise AND for faster index calculation.


What If We Pass Any Capacity Manually?

Example:

new HashMap<>(20);

Internally:

  • HashMap converts 20 to 32

  • Nearest power of 2 is used

So actual internal capacity becomes:

32

This is done automatically.

Interview point:

HashMap internally adjusts capacity to the nearest power of 2.


How This Reduces Collisions

HashMap also improves hash distribution using this step:

hash = h ^ (h >>> 16);

Together with:

index = (n - 1) & hash;

This ensures:

  • Even distribution of keys

  • Better use of all buckets

  • Fewer collisions

  • Faster get() and put() operations


Final Interview-Ready Explanation

You can say this confidently in interviews:

HashMap capacity is always a power of 2.
Because of that, HashMap uses (n - 1) & hash instead of modulo to calculate bucket index.
This is faster and ensures uniform key distribution.


One-Line Summary

Power of 2 → Bitmask → Fast index calculation → Fewer collisions


Comments

Popular posts from this blog

Java Backend Developer Roadmap 2026 (Complete Step-by-Step Guide)

Java Backend Developer Roadmap 2026 (Step-by-Step Guide) Becoming a Java Backend Developer in 2025 is an excellent career choice. Java continues to dominate enterprise applications, microservices, cloud-native systems, and large-scale backend engineering. But the real challenge is knowing what to learn and in what order . This roadmap simplifies everything. Follow it step-by-step and you will gain the exact skills companies expect from a backend engineer — beginner to advanced, in the right sequence. Why Java Backend Is Still a Great Choice in 2026 Java remains the most widely adopted enterprise backend language. Modern Java (17/21/23) includes features like records, sealed classes, pattern matching, and virtual threads, making it more productive than ever. Spring Boot continues to lead backend development, powering microservices in companies of all sizes. Java has unmatched job availability across startups, MNCs, fintech, e-commerce, cloud companies, and global product...

How to Prepare for Java Interviews in 2026 — Complete Roadmap for Developers

How to Prepare for Java Interviews in 2026 — Complete Roadmap for Developers Table of Contents Introduction Understand the 2025 Hiring Trend Core Java Fundamentals Collections & Data Structures Multithreading & Concurrency Java 8–21 Features Spring Boot Essentials Microservices Interview Prep SQL & Database Concepts REST APIs System Design Coding Round (DSA) Sample Daily Preparation Routine Final Tips 1. Introduction Java interviews are evolving rapidly. Companies in 2025 expect backend developers who not only understand Core Java but also have strong skills in Spring Boot, microservices, SQL, concurrency , and system design . The good news? With a structured roadmap, Java interview preparation becomes predictable and achievable. In this guide, I’ll walk you through the exact topics you should master — with the same clarity I use in my YouTube tutorials and Udemy courses . If you are following this guide seriously, make sure ...

Python Development Crash Guide 2026 — Part 2: Core Python: Syntax, Control Flow, Functions & Data Structures

 🐍 Python Development Crash Guide 2026 — Part 2:Core Python: Syntax, Control Flow, Functions & Data Structures This part transforms you from “I know Python basics” to “I can actually write Python code confidently.” If Part-1 was about understanding Python , Part-2 is about thinking in Python . This post focuses on: Writing correct, readable Python code Understanding how Python makes decisions Organizing logic using functions Mastering Python’s core data structures (deeply, not superficially) These concepts are mandatory for: Backend development Automation Data science Interviews Clean, maintainable code 📌 What This Part Covers In this post, you will learn: Python control flow and decision making Boolean logic and truthy / falsy values Loops and iteration (deep understanding) Functions and parameter handling Python’s execution flow and call stack (intro) Core data structures (lists, tuples, sets, dictionaries) Mutability, performance implications, and common mistakes Chapter...