Sobes.tech
Junior — Middle

Explain the mechanism of the linked hash table LinkedHashMap and its features.

sobes.tech AI

Answer from AI

LinkedHashMap is an implementation of the Map interface in Java that combines a hash table and a linked list to store elements.

Features and working mechanism:

  • It is based on a hash table that provides fast access to elements by key (usually O(1)).
  • A doubly linked list is used to preserve the order of elements, linking all entries in insertion or access order.
  • The iteration order corresponds either to the insertion order (default) or access order (if accessOrder mode is enabled).
  • When a new element is inserted, it is added to the end of the linked list.
  • When an element is accessed (if access mode is enabled), it is moved to the end of the list, which is useful for implementing LRU caches.

Example of creating a LinkedHashMap with access order:

LinkedHashMap<Integer, String> map = new LinkedHashMap<>(16, 0.75f, true);
map.put(1, "one");
map.put(2, "two");
map.get(1); // now the element with key 1 is considered the most recently accessed

Thus, LinkedHashMap allows efficient storage of key-value pairs while maintaining element order.