Which Java collection lets you associate elements with keys while iterating in insertion (FIFO) order?
-
Ajava.util.ArrayList
-
Bjava.util.LinkedHashMap
-
Cjava.util.HashMap
-
Djava.util.TreeMap
-
Ejava.util.PriorityQueue
Answer
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:
- We need key–value association (i.e., a Map).
- We want predictable iteration order: specifically insertion order (FIFO-like).
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:
Eliminate non-Map types: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