What is HashMap and how it works?

Asep Saputra
Code Storm
Published in
5 min readMar 19, 2023

--

source: educba

What is HashMap?

HashMap is a class in Java that provides a way to store and retrieve key-value pairs. It is part of the Java Collections Framework and is based on the hash table data structure.

How it works?

In a HashMap, each key is mapped to a value, which can be any Java object. The key must be unique within the HashMap, but the same value can be associated with multiple keys.

The HashMap class provides methods to add, remove, and retrieve elements from the map. The put() method is used to add a key-value pair to the map, the remove() method is used to remove a key-value pair, and the get() method is used to retrieve the value associated with a key.

Hashing is used to provide fast access to the elements in the map. When a key-value pair is added to the map, the key is hashed to generate an index into an array of buckets. Each bucket contains a linked list of elements with the same hash code. When a key is used to retrieve a value, its hash code is used to locate the appropriate bucket, and the linked list is searched for the key.

What is the advantage of HashMap?

HashMap has several advantages over other data structures:

  1. Fast Retrieval: HashMap provides constant…

--

--