Posts

Showing posts with the label Collections

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 ...