File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
Section 25 Collections Frameworks/Map Interface/Linked HashMap/src Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ How a normal LinkedHashMap vs a LinkedHashMap with accessOrder = true + removeEldestEntry()` (LRU Cache) behaves.
2+
3+ ⸻
4+
5+ Case 1: Normal LinkedHashMap (Insertion Order):
6+
7+ Capacity doesn’t matter here since it doesn’t evict automatically.
8+
9+ Start: (empty)
10+
11+ put(A) → [A]
12+ put(B) → [A → B]
13+ put(C) → [A → B → C]
14+
15+ get(A) → [A → B → C] // No reordering
16+ put(D) → [A → B → C → D] // Just keeps growing
17+
18+ Insertion order is preserved. No eviction.
19+
20+ ⸻
21+
22+ Case 2: LinkedHashMap with accessOrder = true (LRU Mode)
23+
24+ Assume capacity = 3 and removeEldestEntry() removes oldest when size > 3.
25+
26+ Start: (empty)
27+
28+ put(A) → [A]
29+ put(B) → [A → B]
30+ put(C) → [A → B → C]
31+
32+ get(A) → [B → C → A] // A moved to end (most recently used)
33+
34+ put(D) → capacity exceeded!
35+ → Evict B (least recently used)
36+ → [C → A → D]
37+
38+ get(C) → [A → D → C] // C moved to end
39+
40+ put(E) → capacity exceeded!
41+ → Evict A
42+ → [D → C → E]
43+
44+ ⸻
45+
46+ Observations
47+ • Normal LinkedHashMap:
48+
49+ Just keeps keys in the order they were inserted, forever.
50+ • LinkedHashMap (LRU mode):
51+ • Every get() or put() moves the key to the end.
52+ • Once size > capacity, the eldest entry (front of the list) is evicted.
53+ • Ensures that only the most recently used items are kept.
54+
55+ ⸻
56+
57+ That’s why LinkedHashMap(accessOrder=true) + removeEldestEntry() = ready-made LRU Cache implementation.
58+
59+ ⸻
You can’t perform that action at this time.
0 commit comments