Difficulty: Easy
Correct Answer: java.util.LinkedHashMap
Explanation:
Introduction / Context:
Different Java collections provide different ordering guarantees. The question asks for a map (key–value association) that also preserves insertion order, enabling FIFO-style iteration.
Given Data / Assumptions:
Concept / Approach:LinkedHashMap
combines a hash table with a doubly-linked list to maintain predictable iteration order. By default, it preserves insertion order; alternatively, it can be configured for access order. Other map implementations either do not preserve order (HashMap
) or impose a sort order by key (TreeMap
), not insertion order.
Step-by-Step Reasoning:
ArrayList
and PriorityQueue
are not maps.Consider map types: HashMap
→ no order guarantee; TreeMap
→ sorted by key; LinkedHashMap
→ preserves insertion order.
Verification / Alternative check:
Quick test inserting keys A, B, C into a LinkedHashMap
and iterating shows A, B, C order.
Why Other Options Are Wrong:ArrayList
lacks keys; HashMap
is unordered; TreeMap
orders by key comparator; PriorityQueue
is a heap, not key–value store.
Common Pitfalls:
Confusing insertion order with sorted order; assuming HashMap
iteration order is stable (it is not guaranteed).
Final Answer:
java.util.LinkedHashMap
Discussion & Comments