HashMap Internal Working in Java Explained Simply
HashMap in Java stores data in an array of buckets using a hashCode() of the key to find the right bucket. If multiple keys map to the same bucket, it uses a linked list or tree to store entries, enabling fast retrieval by key.How It Works
Imagine a HashMap as a set of mailboxes (buckets), each holding letters (key-value pairs). When you add a key-value pair, Java uses the key's hashCode() to decide which mailbox to put the letter in. This process is called hashing.
Sometimes, two different keys might get the same mailbox number. When this happens, Java stores these letters in a linked list or a balanced tree inside that mailbox to keep them organized. When you want to find a value by its key, Java again uses the key's hashCode() to find the mailbox, then searches inside the list or tree for the exact key.
This method makes looking up values very fast, usually close to instant, because it avoids searching through all entries.
Example
This example shows how to create a HashMap, add key-value pairs, and retrieve a value by key.
import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("apple", 10); map.put("banana", 20); map.put("orange", 30); System.out.println("Value for key 'banana': " + map.get("banana")); } }
When to Use
Use a HashMap when you need to store data as key-value pairs and want fast access to values using keys. It is ideal for cases like caching data, counting occurrences, or any situation where quick lookup, insertion, and deletion are important.
For example, a phone book app can use a HashMap to quickly find a phone number by a person's name.
Key Points
- Hashing: Uses key's
hashCode()to find bucket. - Buckets: Array slots holding entries.
- Collision Handling: Uses linked lists or trees inside buckets.
- Fast Access: Average O(1) time for get/put operations.
- Resize: Automatically grows when many entries cause collisions or load factor threshold is exceeded.