Detailed Explanation: Map & HashMap Internal Working:
ekanadhreddy kakularapu

Detailed Explanation: Map & HashMap Internal Working:

Map Interface:

  • Map is not a class, it’s an interface in java.util package.
  • It stores key-value pairs.
  • Keys must be unique, but values can be duplicate.
  • Implementations: HashMap, TreeMap, LinkedHashMap, etc.


HashMap Class:

  • Most commonly used implementation of Map.
  • Stores data in buckets using a technique called Hashing.
  • Allows one null key and multiple null values.
  • Not synchronized, so not thread-safe by default.


Step-by-Step: How HashMap Works Internally

Map<String, String> map = new HashMap<>();
map.put("UNITEDSTATES", "TEXAS");
        

Step-by-Step:

1.Hash Code Calculation:

Java uses hashCode() of the key.

For "UNITEDSTATES", it calls "UNITEDSTATES ".hashCode(), e.g., returns 2344567.

2.Index Calculation:

HashMap uses the hash code to find a bucket index:

index = hash(key.hashCode()) % capacity;
        

Suppose capacity = 16, index = 2344567 % 16 = 7.

3.Node Insertion:

  • A new Node object is created: Node{key="UNITEDSTATES", value="TEXAS", hash=2344567}.
  • Stored at bucket index 7.
  • If the bucket is empty — it's inserted directly.

4. Collision Handling:

  • If another key hashes to the same bucket (collision), Java uses:
  • Linked List (pre Java 8)
  • Balanced Tree (Java 8+) when list > 8 elements to improve lookup time (from O(n) to O(log n))


5.Retrieval (get method):

  • map.get("UNITEDSTATES"):
  • Calculates hash.
  • Goes to bucket index 7.
  • Scans through the list/tree to match key using equals().

Real-Time Example:

Imagine a Banking System:

A HashMap<String, Customer> stores customer data using Account Numbers as keys.

Map<String, Customer> customerMap = new HashMap<>();
customerMap.put("ACC12345", new Customer("John", "Premium"));
        

Why HashMap?

  • Quick lookup when user logs in (O(1) average).
  • Fast performance with large datasets.

In the backend:

  • Account number’s hash code is used to find the storage bucket.
  • Lookup is instant due to hashing.


HashMap uses hashing to store key-value pairs in an array of buckets. It computes hashCode and then applies internal hash function to find the right index. On collision, it uses LinkedList or TreeMap depending on the number of items. Retrieval is fast — ideally O(1), and TreeMap ensures performance doesn’t degrade beyond O(log n)."

Thank you,

Ekanadhreddy Kakularapu

To view or add a comment, sign in

More articles by Ekanadh Reddy

Insights from the community

Others also viewed

Explore topics