Internal Working of Java HashMap

🔍 What is Java HashMap? Working Explained with Example

Java HashMap is a powerful data structure from the Java Collections Framework that stores elements as key-value pairs. It allows fast access to data by leveraging hashing, making operations like insertion, lookup, and deletion highly efficient. HashMap is ideal when you need to associate unique identifiers (keys) with specific values.

⚙️ How HashMap Works

  • Key-Value Structure: Each entry in the map consists of a unique key and its corresponding value.
  • Hashing Mechanism: HashMap uses the key’s hashCode() to determine the bucket index where the entry will be stored.
  • Bucket Allocation: Internally, HashMap maintains an array of buckets. Each bucket can hold multiple entries in case of hash collisions.
  • Collision Handling: If two keys produce the same hash code, their entries are stored in a linked list or balanced tree within the same bucket.
  • Key Uniqueness: Keys must be unique. If a duplicate key is inserted, the new value replaces the old one.

🛠️ How put() and get() Work

put(key, value): Adds or updates a key-value pair.

  • Generates the hash code of the key.
  • Calculates the bucket index using the hash code.
  • If the bucket is empty, the entry is added directly.
  • If the bucket contains entries, it checks for key equality using equals().
  • If the key exists, the value is updated; otherwise, the new entry is appended.

get(key): Retrieves the value associated with a key.

  • Computes the hash code of the key.
  • Locates the bucket index.
  • Searches the bucket for a matching key using equals().
  • Returns the value if found; otherwise, returns null.

🔄 Handling Collisions

When multiple keys map to the same bucket due to identical hash codes, HashMap stores them in a linked list or a red-black tree (if the list exceeds a threshold). The equals() method ensures that keys are correctly identified even in collision scenarios.

📈 Rehashing and Load Factor

Load Factor: Determines when the HashMap should resize. The default is 0.75, meaning the map resizes when 75% of the buckets are filled.

Rehashing: When the number of entries exceeds capacity × load factor, the map expands (usually doubling the bucket count) and redistributes existing entries to new buckets.

🔧 Basic Operations

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

💻 Example Code


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 conclusion, Java HashMap is a versatile and high-performance data structure ideal for scenarios where fast access to data is crucial. Its internal hashing mechanism, collision handling, and dynamic resizing make it a go-to choice for developers working with key-value mappings.