☕ Java Intermediate

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.