Internal Working of Java HashMap

What is Java HashMap? Working Explained with Example

Java HashMap is a data structure that stores data in key-value pairs, allowing efficient retrieval, insertion, and deletion of values based on their keys. It uses hashing to map keys to buckets, enabling fast access.

How HashMap Works

  • Key-Value Pairs: Each entry consists of a unique key and an associated value.
  • Hashing: HashMap computes a hash code for each key to determine its storage bucket.
  • Buckets and Collisions: If multiple keys map to the same bucket (collision), entries are stored in a linked list or tree within that bucket.
  • Uniqueness: Keys must be unique. Adding a value with an existing key overwrites the old value.

How put() and get() Work

put(key, value):
  • Computes the hash code of the key.
  • Determines the bucket index using the hash code.
  • If the bucket is empty, the key-value pair is added.
  • If the bucket already contains entries, it checks each entry using equals() to see if the key already exists.
  • If it exists, the value is updated.
  • If not, the new entry is added to the bucket’s linked list.
get(key):
  • Computes the hash code of the key.
  • Determines the bucket index.
  • Searches the bucket for an entry with the matching key using equals().
  • Returns the value if found, otherwise returns null.

Handling Collisions

When two keys have the same hash code, their entries are stored in a linked list (or tree if the list gets too long) within the same bucket. The equals() method is used to distinguish between different keys with the same hash code.

Rehashing and Load Factor

Load Factor: Determines when to increase the number of buckets. The default load factor is 0.75, and the default initial capacity is 16.

Rehashing: When the number of entries exceeds the threshold (capacity × load factor), the HashMap increases its capacity (always a power of 2) and redistributes the entries.


Basic Operations

  • put(key, value): Adds or updates a key-value pair.
  • get(key): Retrieves the value for a given key.
  • remove(key): Removes the mapping for a key.
  • containsKey(key): Checks if a key exists.

Example


import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, String> capitalCities = new HashMap<>();
        capitalCities.put("England", "London");
        capitalCities.put("India", "New Delhi");
        capitalCities.put("Austria", "Vienna");
        capitalCities.put("Norway", "Oslo");
        capitalCities.put("USA", "Washington DC");

        System.out.println(capitalCities.get("India")); // Output: New Delhi
        System.out.println(capitalCities); // Prints all key-value pairs
    }
}

Output:
New Delhi
{England=London, India=New Delhi, Austria=Vienna, Norway=Oslo, USA=Washington DC}

Summary Table

Operation Description
put(key, val) Adds or updates a key-value pair
get(key) Retrieves value for a given key
remove(key) Removes the mapping for a key
containsKey(key) Checks if a key exists
keySet() Returns a set of all keys
values() Returns a collection of all values

In summary, HashMap provides fast, constant-time average performance for basic operations, thanks to its use of hashing and efficient handling of collisions and resizing.