Java — Which Map implementation maintains iteration order of an existing Map?
Java Programming
Objects and Collections
Difficulty: Medium
Choose an option
-
ATreeMap
-
BHashMap
-
CLinkedHashMap
-
DThe answer depends on the implementation of the existing instance.
Answer
Correct Answer: LinkedHashMap
Explanation
Introduction / Context:This question tests knowledge of different Map implementations in Java and their ordering characteristics.
Concept / Approach:
- HashMap → no ordering guarantee.
- TreeMap → natural or custom comparator order, not iteration order.
- LinkedHashMap → maintains insertion order or access order.
Step-by-Step Reasoning:
If you want the iteration order of an existing Map to be preserved, use LinkedHashMap and construct it with the existing Map.Why Other Options Are Wrong:TreeMap re-sorts keys, HashMap randomizes order, and "depends on implementation" is too vague.
Final Answer:LinkedHashMap