Sobes.tech
Senior

What is the difference between HashMap and LinkedHashMap?

sobes.tech AI

Answer from AI

Main differences between HashMap and LinkedHashMap:

  • Order of elements:

    • HashMap does not guarantee the order of elements during iteration.
    • LinkedHashMap maintains the insertion order of elements (or access order if access-order is enabled).
  • Performance:

    • HashMap is slightly faster due to the absence of an additional structure for order.
    • LinkedHashMap is slightly slower because it supports a linked list for order.
  • Usage:

    • HashMap is suitable when order does not matter.
    • LinkedHashMap is convenient when a predictable iteration order is needed, such as for caches.

Example of using LinkedHashMap for a cache with removal of old elements:

LinkedHashMap<K, V> cache = new LinkedHashMap<K, V>(initialCapacity, loadFactor, true) {
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > MAX_ENTRIES;
    }
};