Sitemap

Member-only story

Behind the Scenes: How LinkedHashMap Works in Java

6 min readJun 18, 2018

--

The LinkedHashMap in Java combines the functionality of a HashMap with the ability to maintain the insertion order of entries. Unlike HashMap, which has no predictable order, LinkedHashMap preserves the order in which keys are inserted. This makes it useful in applications where ordered storage and retrieval of key-value pairs are required. Let's dive into how the LinkedHashMap works internally, including its structure, additional fields, and mechanisms for maintaining insertion order.

Understanding HashMap Basics (Pre-requisite)

Before exploring LinkedHashMap, it’s essential to understand the underlying mechanisms of HashMap, as LinkedHashMap builds upon HashMap with additional functionality. Here are some important points to keep in mind about HashMap(refer https://goo.gl/tMVF3g article for detailed explanation):

  1. Storage Structure: HashMap stores key-value pairs in Node objects, which are placed in an internal array (table) indexed by the hash code of the keys.
  2. put() Method:
    When calling put(key, value), if a node with the same key exists, the method replaces its value and returns the old value.
    If the key is new, put() returns null as it inserts the key-value pair for the first time.
  3. get() Method:
    If a key does not exist, get(key) returns null.
    If the key exists, get() retrieves the value associated with that key.
  4. Iteration Order: When iterating over a HashMap, the…

--

--

Anmol Sehgal
Anmol Sehgal

Written by Anmol Sehgal

Senior Software Developer @ Amazon | ex Oracle OCI, Goldman Sachs, Expedia | Writing real-world lessons on Java, system design & production-scale architecture.

Responses (5)