Sobes.tech
Junior — Middle

How does the order of elements in LinkedHashMap depend on recent access to them?

sobes.tech AI

Answer from AI

In the LinkedHashMap class in Java, the order of elements can depend on the order of insertion or access, depending on the constructor parameter accessOrder.

If accessOrder is set to false (the default), then the order of elements corresponds to the order in which they were inserted — elements are enumerated in the order they were added.

If accessOrder is set to true, then the order of elements changes upon access (for example, when calling get(), put(), or putAll() for an existing key). In this case, the element that was recently accessed is moved to the end of the list, reflecting its recent use. This behavior is useful, for example, for implementing caches with an LRU (Least Recently Used) policy.

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 recently used
// During iteration, the element with key 1 will come after the key 2
How does the order of elements in LinkedHashMap… - sobes.tech