☕ Java Intermediate

What is the difference between HashMap and LinkedHashMap?

Why Interviewers Ask This

This question targets practical, hands-on experience with Java. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

HashMap does not guarantee any order of iteration — the order of entries may seem random. LinkedHashMap extends HashMap and maintains a doubly-linked list across all entries, guaranteeing that iteration order is the insertion order (the order in which key-value pairs were added). This makes LinkedHashMap slightly slower and more memory-intensive than HashMap, but the predictable iteration order is often worth it. LinkedHashMap also supports access-order mode (pass true as the third constructor argument), which moves recently accessed entries to the end — this is the basis of building an LRU (Least Recently Used) cache.

Pro Tip

This topic has Java-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.