What is a HashMap and how does it work?
168
19-Jul-2024
Updated on 19-Jul-2024
Ashutosh Kumar Verma
19-Jul-2024Java HashMap
In Java, HashMap is a data structure that implements the Map interface and stores key-value pairs. It uses hash tables to store elements, allowing you to quickly retrieve values based on their keys.
Working of HashMap
Hashing
HashMap
usingput(key, value)
, theHashMap
calculates the hash code of the key. This hash code is used to determine the bucket (or index) in which the key value pair will be stored.Bucket Storage
HashMap
is divided into blocks called buckets. Each bucket can contain multiple key-value pairs. The index of the bucket is determined by applying the hash function to the hash code of the key.HashMap
uses a linked list (or a balanced tree in other Java versions for better performance) to store more information in a bucket.Retrieval
HashMap
withget(key)
, theHashMap
recalculates the hash code of the key to find a matching bucket.equals()
method to compare).Performance
HashMap
provides a constant time operation (O(1)) for theget()
andput()
operations, assuming that the hash operation disperses the items efficiently in the bucket.Example-
In the example above
AHashMap is used to store mappings from integers (keys) to strings (values). The
put()
method adds entries,get()
retrieves key-based values, andkeySet()
allows iterating over all keys.Also, Read: What is the difference between wait() and sleep() in Java?