LinkedHashMap
About
LinkedHashMap
is a subclass of HashMap
introduced in Java 1.4. It maintains the order of elements, unlike HashMap
, which is unordered. This class is part of the java.util
package and implements the Map
interface. The order of elements can be insertion order or access order, depending on the configuration.
Insertion Order: The order in which entries are inserted is preserved.
Access Order: The order is updated based on recent access if configured.
Features
Preserves Order: Maintains insertion or access order.
Backed by HashMap: Internally uses a
HashMap
for storage.Doubly Linked List: Maintains a linked list of entries for ordering.
Allows Null Keys and Values: Similar to
HashMap
, it allows onenull
key and multiplenull
values.Not Thread-Safe: By default, it is not synchronized. Use
Collections.synchronizedMap()
for thread-safe operations.Performance: Slightly slower than
HashMap
due to linked list maintenance but faster thanTreeMap
for ordered operations.
Internal Working
The LinkedHashMap
combines the functionality of HashMap
with a doubly linked list to maintain insertion or access order.
Data Structure
LinkedHashMap
relies on two main data structures:
HashMap:
Stores the key-value pairs in an array of buckets.
Each bucket contains a singly linked list (or a tree for large buckets in modern Java versions).
Hashing is used to distribute keys uniformly across buckets.
Doubly Linked List:
Maintains the order of entries.
Each entry in
LinkedHashMap
is linked to the previous and next entries using two additional pointers (before
andafter
).
Components
Entry Class: Each entry in
LinkedHashMap
is represented by an inner classLinkedHashMap.Entry<K, V>
, which extendsHashMap.Node<K, V>
. It has two extra fields:before
: Points to the previous entry in the linked list.after
: Points to the next entry in the linked list.
Head and Tail Pointers:
The doubly linked list is anchored by a
head
andtail
.The
head
points to the first inserted entry.The
tail
points to the most recently inserted (or accessed, in access-order mode) entry.
How Order Is Maintained
Insertion Order:
When a new entry is added, it is appended to the end of the doubly linked list.
This preserves the order of insertion.
Access Order:
If
accessOrder
is set totrue
, the linked list is updated every time an entry is accessed (viaget
,put
, orputIfAbsent
methods).The accessed entry is moved to the end of the list.
Rehashing
Triggered when the size exceeds the load factor threshold.
The
HashMap
resizes its bucket array, and entries are rehashed to new buckets.During rehashing:
The linked list structure is preserved.
The
before
andafter
pointers of all entries remain intact.
Operations
put(K key, V value)
Calculates the hash for the key.
Determines the bucket index based on the hash.
Checks if the key already exists:
If yes, updates the value.
If no, creates a new
Entry
.
Inserts the entry in the
HashMap
.Updates the doubly linked list:
Links the new entry to the current
tail
.Updates the
tail
pointer.
get(Object key)
Uses the hash to locate the bucket.
Searches for the key in the bucket’s chain.
If the key is found:
Returns the value.
Updates the order in the doubly linked list if
accessOrder
istrue
.
remove(Object key)
Locates the entry in the
HashMap
using the hash.Removes the entry from the bucket's chain.
Updates the doubly linked list:
Unlinks the entry from its
before
andafter
neighbors.Adjusts the
head
ortail
pointers if necessary.
Key Methods
Method
Description
put(K key, V value)
Adds a key-value pair. If the key exists, updates the value.
get(Object key)
Retrieves the value associated with the key. Updates order if accessOrder
is true
.
remove(Object key)
Removes the key-value pair for the specified key.
containsKey(Object key)
Checks if the map contains the specified key.
containsValue(Object value)
Checks if the map contains the specified value.
keySet()
Returns a Set
of keys in order.
values()
Returns a Collection
of values in order.
entrySet()
Returns a Set
of key-value mappings in order.
clear()
Removes all mappings.
removeEldestEntry(Map.Entry<K,V>)
Determines whether to remove the eldest entry when a new entry is added.
Big-O for Operations
Operation
Average Case
Worst Case
Put
O(1)
O(n)
Get
O(1)
O(n)
Remove
O(1)
O(n)
Iteration
O(n)
O(n)
Limitations
Memory Overhead: The doubly linked list adds memory overhead compared to
HashMap
.Not Thread-Safe: Requires external synchronization for concurrent use.
Slightly Slower Than
HashMap
: Maintaining order introduces additional overhead.Unpredictable Behavior with Null Keys: While it allows
null
keys, unexpected behaviors may occur ifnull
is frequently accessed in access-order mode.
Real-World Usage
Caches: Used to implement Least Recently Used (LRU) caches by overriding
removeEldestEntry()
.Maintaining Order: Useful in applications where insertion or access order is critical.
Data Stores: Ideal for implementing ordered data stores, like log files or access history.
Examples
1. Basic Operations
2. Access Order
3. Implementing LRU Cache
Last updated
Was this helpful?