Java / Java 21 Collection Framework features Interview questions
Explain the execution flow of putFirst() on a LinkedHashMap?
Internally, LinkedHashMap maintains a doubly linked list threaded through its entries in addition to the usual hash table, and that linked list is what actually defines the map's encounter order.
sequenceDiagram
participant Caller
participant LinkedHashMap
participant HashTable
participant LinkedList as Internal Linked List
Caller->>LinkedHashMap: putFirst(key, value)
LinkedHashMap->>HashTable: Check if key exists
alt Key exists
LinkedHashMap->>LinkedList: Unlink existing entry
end
LinkedHashMap->>HashTable: Insert/update key-value pair
LinkedHashMap->>LinkedList: Link entry at the head
LinkedList-->>LinkedHashMap: Head pointer updated
LinkedHashMap-->>Caller: Return previous value or null
If the key already existed somewhere in the map, its old node is first unlinked from wherever it sat in the linked list; if it's new, a fresh node is created. Either way, the node is then linked in at the head of that internal list, which is what makes it the new "first" entry for iteration and for firstEntry().
The hash table itself is used only for the O(1) key lookup - the actual iteration order that firstEntry(), lastEntry(), and reversed() rely on comes entirely from the linked list, not from hash bucket order.
More Related questions...