Member-only story
Internal Working of HashSet and Changes in Java 8
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:
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…