Understanding HashMap Initial Capacity and Proper Usage in Java

This article explains why specifying an initial capacity for Java's HashMap matters, demonstrates common mistakes, walks through the source‑code calculation of the capacity and resize threshold, and provides guidelines on choosing the correct capacity to avoid unnecessary rehashing and improve performance.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Understanding HashMap Initial Capacity and Proper Usage in Java

Preface

Although I have been blogging for a long time, I rarely write about HashMap because it is a common interview topic that many readers have already seen.

The reason I decided to write this article now is that I recently reviewed old project code at work and discovered many developers misuse HashMap's initial capacity.

Content Overview

Examples of incorrect usage when specifying capacity;

Source‑code walkthrough of how HashMap calculates its initial capacity;

Points where resizing occurs;

Correct usage guidelines; and

Some additional discussion.

Why Specify Capacity?

The core reason is to avoid repeated resizing as the map grows, which can degrade performance.

Incorrect Example ①

Creating a map for a paginated query that always returns at most 15 items: Map<String, String> map = new HashMap<>(15); or

Map<String, String> map = new HashMap<>(userPageList.size());

Incorrect Example ②

Storing four different types in a map:

Map<Integer, String> map = new HashMap<>(4);

Incorrect Example ③

Creating a map that will hold only two entries: Map<String, String> map = new HashMap<>(2); All these examples misuse the capacity value.

How Capacity Is Calculated

When you pass an initial capacity c, HashMap actually uses c * 0.75 as the resize threshold. For example, passing 4 results in a threshold of 3, so inserting the fourth element triggers a resize.

Reflection Demo

public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {<br/>    Map<String, String> map = new HashMap<>(4);<br/>    Class<?> mapType = map.getClass();<br/>    Method capacity = mapType.getDeclaredMethod("capacity");<br/>    capacity.setAccessible(true);<br/>    map.put("1", "first");<br/>    System.out.println("capacity : " + capacity.invoke(map) + "    size : " + map.size());<br/>    map.put("2", "second");<br/>    System.out.println("capacity : " + capacity.invoke(map) + "    size : " + map.size());<br/>    map.put("3", "third");<br/>    System.out.println("capacity : " + capacity.invoke(map) + "    size : " + map.size());<br/>    map.put("4", "fourth");<br/>    System.out.println("capacity : " + capacity.invoke(map) + "    size : " + map.size());<br/>}

The output shows that after inserting three elements the capacity remains 4, but inserting the fourth element triggers a resize to 8.

Choosing the Right Capacity

To avoid resizing, compute the needed capacity as desiredSize / 0.75 + 1. For storing four elements, the calculation yields about 6.33, so using an initial capacity of 6 or 7 (both rounded up to the next power of two, 8) prevents an extra resize.

HashMap always rounds the internal table size up to the next power of two, so capacities 5‑8 all result in an internal size of 8, and 9‑16 result in 16.

Conclusion

Specifying the initial capacity is a trade‑off between memory usage and performance; use it when you have a good estimate of the number of entries, especially in memory‑constrained or high‑throughput scenarios.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

hashmapCollectionsinitial capacity
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.