Posts

Showing posts with the label Collections Framework

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

ArrayList vs LinkedList in Java

Image
Java’s Collections Framework provides two commonly used List implementations: ArrayList and LinkedList . While both implement the List interface , they differ in their underlying data structures, performance, and use cases. Let’s break down their differences with examples and diagrams. 1. Underlying Structure ArrayList → Backed by a dynamic array. Elements are stored in contiguous memory . LinkedList → Implemented as a doubly-linked list. Each node stores data + pointers to the previous and next node. Diagram: ArrayList (Dynamic Array) [ 0 ] → [ 1 ] → [ 2 ] → [ 3 ] → [ 4 ] (index based access) LinkedList (Doubly Linked Nodes) NULL ← [0 | *] ↔ [1 | *] ↔ [2 | *] ↔ [3 | *] → NULL 2. Code Example ArrayList Example: import java.util.*; public class ArrayListExample { public static void main(String[] args) { List list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C+...