What is the difference between HashMap and LinkedHashMap?
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.
Previous
What is the difference between HashMap and HashTable in Java?
Next
What is the difference between HashSet and TreeSet?
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashSet and TreeSet?