Back to Browse

Java HashMap Deep Dive

21 views
May 10, 2026
12:52

a comprehensive look into the internal mechanics of Java's HashMap, covering everything from basic performance to advanced optimizations in modern Java versions. 🏗️ 1. Core Architecture & Performance * O(1) Complexity: The HashMap acts as a "bucket array" that uses a specialized hashing function to map keys to specific memory locations, enabling near-constant time performance 01:14 . * Indexing Optimization: Modern Java uses a bitwise AND mask (n-1) & hash instead of the slower modulo operator to calculate bucket indices 02:19 . * Capacity: The array length is always a power of two to support these fast bitwise calculations 02:32 . 🛡️ 2. Handling Collisions (Java 8+ Improvements) * Chaining & Treeification: When multiple keys map to the same bucket, they are initially stored in a Linked List. Once a bucket reaches 8 nodes (the Tree Threshold), it transforms into a Red-Black Tree 03:04 . * Performance Safety: This "treeification" ensures that even under heavy collisions, the worst-case search time is reduced from $O(n)$ to $O(\log n)$ 04:41 . * The Poisson Distribution: The threshold of 8 was chosen because the statistical probability of a bucket naturally reaching that size is extremely low ($ 0.6\%$) 03:47 . 📈 3. Resizing & Memory Management * Load Factor (0.75): Once the map is 75% full, a "rehashing" event doubles the capacity 05:01 . * Efficient Expansion: Because capacity is a power of two, Java only needs to check a single bit in the hash code to determine if an entry stays at its index or shifts to the new space 06:19 . * Thread Safety Warning: While Java 8 fixed an infinite loop bug caused by "head insertion," the HashMap remains thread-unsafe. Use ConcurrentHashMap for multi-threaded environments 07:12 . 📜 4. The Hashing Contract & Best Practices * The Contract: If two objects are equal via .equals(), they must return the same .hashCode(). Overriding one without the other leads to unretrievable data 07:32 . * Immutability: Use immutable objects (like String or Integer) as keys. Changing a key's properties after insertion changes its hash code, effectively "losing" the object in memory 08:21 . * New Factory Methods: Since Java 19, developers should use HashMap.newHashMap(int expectedSize) to automatically handle load factor math and prevent expensive resizing 10:46 . 🌲 5. The Map Ecosystem * LinkedHashMap: Maintains insertion order using a doubly linked list 09:24 . * TreeMap: Keeps keys sorted alphabetically or numerically using a red-black tree 09:38 . * Memory Footprint: Be aware of overhead; each node in a standard HashMap carries roughly 32 bytes of overhead 10:04 . A Channel to share useful knowledge / Skill 🤓 一個開心share 實用小知識 / 技巧既channel 😆

Download

0 formats

No download links available.

Java HashMap Deep Dive | NatokHD