Java / Java 21 Collection Framework features Interview questions
How does LinkedHashMap's access-order mode interact with SequencedMap methods?
A LinkedHashMap can be constructed with accessOrder = true, which changes its encounter order so that reading an entry via get() moves it to the end, rather than leaving the order fixed at insertion time.
LinkedHashMap<String, Integer> cache = new LinkedHashMap<>(16, 0.75f, true); // access-order enabled cache.put("a", 1); cache.put("b", 2); cache.get("a"); // moves "a" to the end System.out.println(cache.lastEntry()); // a=1
Because firstEntry(), lastEntry(), and reversed() all reflect whatever the current encounter order is, they behave dynamically under access-order mode - the "first" entry can change simply because something was read, not just because something was added or removed.
This access-order behavior is exactly what powers a classic LRU cache pattern: the least-recently-used entry is always firstEntry(), so it can be evicted with pollFirstEntry() whenever the cache needs to shrink.
More Related questions...