THE GENERAL BLOG

How HashSet Works Internally in Java — Step-by-Step Explanation with Example

Posted on October 19, 2025

Learn how Java’s HashSet works internally with HashMap. This guide explains how hashCode() and equals() ensure uniqueness, how elements are stored in buckets, and why HashSet provides O(1) performance for add and lookup operations.

🧩 What is a HashSet?

A HashSet in Java is a collection that stores unique elements. Under the hood, it’s actually built on top of a HashMap — yes, really!

Each element you add to a HashSet is stored as a key in an internal HashMap, and all the values are just dummy objects.

private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();

So when you do:

set.add("Alice");

it’s equivalent to:

map.put("Alice", PRESENT);

⚙️ Step-by-Step: How HashSet Works Internally

Let’s go through the life of one element being added 👇

Suppose we do:

HashSet<Person> set = new HashSet<>();
set.add(new Person("Alice", 25));

Step 1: Call hashCode()

Java first calls:

int hash = person.hashCode();

to get a numeric value — e.g. 12345.

Step 2: Find the bucket

Java calculates which bucket to store the object in:

bucketIndex = hash % numberOfBuckets;

If the number of buckets is, say, 16:

12345 % 16 = 9

So the object goes into bucket #9.

Step 3: Check for duplicates

In bucket #9:

  • If the bucket is empty → store it there.

  • If not, Java calls equals() to check if an equal object already exists.

    • If equals() returns true → it’s a duplicate, so don’t add it.
    • If equals() returns false → store it in the same bucket (linked list).

Step 4: Store the object

If unique, Java stores it in that bucket:

[9] → Alice(25)

and marks it as a key in the underlying HashMap.

🎨 3️⃣ Visual Diagram

Let’s imagine a HashSet with 8 buckets.

Initial state:
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]

After adding some people:

[0]
[1]
[2]  → Bob(30)
[3]
[4]
[5]  → Alice(25)
[6]
[7]

Now if we add another Alice:

set.add(new Person("Alice", 25));

Steps:

  1. hashCode() = same as old Alice → goes to bucket 5
  2. equals() = true (same name and age)
  3. So HashSet doesn’t add it again.

But if hashCode is same but equals is false:

Two people with same age but different names might land in the same bucket:

[5] → Alice(25) → Alicia(25)

→ Java will store them both but keeps them distinct by checking equals().

🧠 4️⃣ Summary Table

Step What happens Which method is used
Compute hash Finds which bucket hashCode()
Check for duplicates Compares with existing items equals()
Add element Only if not found equal Uses both

🔍 5️⃣ Why it’s efficient

  • Lookup (contains()) and insert (add()) are roughly O(1) time — much faster than an ArrayList which can take O(n) for contains().
  • But only if hashCode() distributes objects evenly.


The Most Popular Blog

The best tips and tricks on managing digital documents

Free tool to convert Excel (.xls/.xlsx) file to PDF online.

When you want to share your spreadsheet data with others who may not have Excel or who need a format that cannot be easily edited, converting to PDF

Read More >

How to convert png to jpg or jpeg online using converteasly ?

Converting PNG images to JPG format can significantly reduce the file size, making it more suitable for web publishing, email attachments, or

Read More >

Understanding the Concept of Inheritance in Java with application

Let's dive into the concept of inheritance more deeply with a lots of examples

Read More >

Exploring JDK 17 Features: A Comprehensive Guide

Java Development Kit (JDK) 17, released in September 2021, is the Long-Term Support (LTS) version of the Java programming language.

Read More >

Simple and Free tool to convert PPT file to PDF online with no restrictions.

When sharing slides with others who may not have PowerPoint or when you want to ensure that the content remains as intended

Read More >

How to convert PDF to Text free online with no restriction ?

Converting PDF to text makes it easier to search for specific words, phrases, or keywords within the document. Text search functionality allows you to quickly locate relevant information

Read More >

Simple steps to split single PDF into multiple PDF online using converteasly

you can extract a single chapter from a large book or isolate specific sections for reference or distribution.

Read More >

How to Unescape JSON Using Converteasly

Are you dealing with escaped JSON that needs to be converted back to its original form?

Read More >

How to convert image to pdf online using converteasly?

A free tool to convert one or multiple images to PDF online, at no-cost, no-registration, and no-installation needed.

Read More >

How to convert Pdf To Docx file online free using converteasly ?

If you have received a document in PDF format but need to continue working on it converting it to DOCX allows you to seamlessly resume

Read More >

How to encode text into base64 format online using converteasly?

In some cases, when passing text data as a parameter in a URL, Base64 encoding can be used to ensure that

Read More >

Free tool to convert text to pdf online with no restriction

A free tool to convert one or multiple text files to PDF online, at no-cost, no-registration, and no-installation needed.

Read More >

Simple steps to delete pages from your PDF file online using converteasly

Merge PDF functionality is helpful for compiling e-books or digital publications. Authors or publishers can combine individual chapters

Read More >

How to unlock password protected PDF online using converteasly ?

Unlocking password-protected PDFs or removing restrictions can streamline document workflows, especially in business or administrative settings.

Read More >

How to compress or reduce image size online using converteasly ?

Compressing images is crucial for optimizing website performance. Large image file sizes can significantly impact page load times, leading to slower website speeds

Read More >

How to convert ODF Formula (.odf) file to PDF online using converteasly ?

Educators can convert course materials, lecture notes, and educational resources from ODF to PDF format for distribution to students

Read More >

Understanding Git and GitHub: A Beginner's Guide with Simple Examples

If you're diving into the world of coding, you've probably heard about Git and GitHub. They're like the dynamic duo of version control, helping developers

Read More >

Understanding the concept of Encapsulation and Polymorphism in java

Encapsulation is a fundamental principle in object-oriented programming (OOP) where the internal state of an object is hidden from outside access.

Read More >

How to convert jpg or jpeg to png online using converteasly ?

Converting JPG to PNG can be useful when you want to compress an image while maintaining its quality.

Read More >

How to convert Rich Text Format (.rtf) file to Epub online free using converteasly ?

Educational institutions and educators can convert RTF-based textbooks, study guides, and educational resources into EPUB format

Read More >

Simple and Free tool to merge multiple Docx file into single Docx online.

When preparing presentations, different team members might be responsible for various sections. A merge DOCX tool lets you bring together

Read More >

How to convert Rich Text Format (.rtf) file to PDF online using converteasly ?

Legal professionals often convert legal documents, agreements, and contracts from RTF to PDF to maintain document integrity and

Read More >

How to protect your PDF file with password online ?

When sharing sensitive or confidential documents, protecting the PDF ensures that only intended recipients can access the content.

Read More >

How to change width and height of image online free ?

Resizing images is crucial for optimizing website performance and improving user experience.

Read More >

Effortlessly Compare JSON Objects & Arrays with Converteasly

Are you getting frusted to compare two json data using online tools ? here is the solution for you.

Read More >

Simple steps to decode Base64 to Text online using converteasly

Some APIs return data in Base64 encoded format, especially when dealing with binary data or non-textual content.

Read More >

How to Convert JPG/PNG to WebP Using Converteasly.com

Optimizing images for the web is essential for faster loading times and better user experience. Converting JPG and PNG images to WebP format is an effective way to achieve this.

Read More >

How to Create and Download Your Digital Signature Securely Online

Draw your signature safely online with Converteasly — fast, free, and privacy-first.

Read More >

How HashSet Works Internally in Java — Step-by-Step Explanation with Example

Understanding HashSet in Java: Internal Working, HashMap Relation, and Efficiency Explained

Read More >

How to Merge one or multiple PDFs into single PDf online ?

Merge PDF functionality is helpful for compiling e-books or digital publications. Authors or publishers can combine individual chapters

Read More >

© 2025 converteasly.com - Made with 💕 for the people of the internet.

Consent PreferencesPrivacy PolicyDisclaimerT&C