Member-only story

Internal Working of HashSet and Changes in Java 8

Sanjay Singh
4 min readSep 30, 2024

--

Introduction

In Java, the HashSet class is a widely used collection that implements the Set interface, allowing for the storage of unique elements. Understanding how HashSet operates internally is crucial for developers looking to optimize their code and improve performance. This article delves into the internal workings of HashSet and highlights significant changes introduced in Java 8 that enhance its efficiency.

1. Internal Working of HashSet

Underlying Data Structure

HashSet internally uses HashMap to store its elements. Whenever you create a HashSet object, one HashMap object is also created. This HashMap is utilized to store the elements added to the HashSet. The elements you add are stored as keys in this HashMap, while the associated value is a constant.

Every constructor of the HashSet class creates one HashMap object. You can observe this in the source code of the HashSet class. Below are some sample code snippets of the constructors:

Internal Working of HashSet and Changes in Java 8
private transient HashMap<E,Object> map;
// Constructor - 1
public HashSet() {
map = new HashMap<>(); // Creating internally backing HashMap object
}
// Constructor - 2
public HashSet(Collection<? extends E> c) {
map = new…

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

Responses (1)