Posts

Showing posts with the label HashMap

How HashMap get() Method Works Internally in Java

Image
The get() method in HashMap is one of the most commonly used operations. Although it looks like a simple key lookup, internally it involves hashing, bucket indexing, and collision handling. In this article, we’ll break down the internal working of HashMap.get() step by step with examples. 1. Hashing the Key When you call map.get(key) , the HashMap computes a hash value using the key’s hashCode() . In Java 8+, this value is further processed with bitwise operations to spread the hash bits and reduce collisions. int hash = hash(key.hashCode()); 2. Finding the Bucket The hash value is then converted into an index in the internal array (called table ) using: int index = (n - 1) & hash; // n = table.length This determines the bucket where the entry might be stored. 3. Searching Inside the Bucket Each bucket can contain: null → no entry stored A single key-value pair A linked list of nodes (if multiple keys hash to the same bucket) A red-blac...

Internal Working of Map & HashMap in Java (Interview Ready)

Image
🔹 Introduction In the Java Collections Framework, both Map and HashMap are essential for working with key-value pairs. This blog dives into their internal mechanics, including how objects are stored and retrieved, how collisions are managed, and what improvements Java 8 brought to the table. 1. What is a Map? A Map<K, V> is a data structure that stores unique keys associated with corresponding values. Common implementations include: HashMap – unordered, allows one null key and multiple null values TreeMap – sorted by keys LinkedHashMap – maintains insertion order 2. How HashMap Works Internally ➡️ Nodes & Buckets Internally, a HashMap uses an array of Node objects , where each node represents a key-value pair plus a pointer for chaining in case of collisions. class Node<K,V> { int hash; K key; V value; Node<K,V> next; } ➡️ Hashing & Index Calculation ...