✅ Why LinkedHashMap
?
LinkedHashMap
maintains a linked list of entries:
- Either in insertion order or
- Access order (when enabled) — which is perfect for caching.
It also provides a protected method:
protected boolean removeEldestEntry(Map.Entry<K, V> eldest)
You can override this to define your invalidation policy (e.g., max size).
🔧 Example: LRU Cache using LinkedHashMap
import java.util.*;
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75f, true); // true = access order
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity; // Evict the oldest (least recently used) entry
}
public static void main(String[] args) {
LRUCache<Integer, String> cache = new LRUCache<>(3);
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
cache.get(1); // Access key 1 (makes it most recently used)
cache.put(4, "D"); // Should evict key 2
System.out.println(cache); // Output: {3=C, 1=A, 4=D}
}
}
🔍 How it works:
accessOrder = true
makes the map reorder entries on eachget()
orput()
.- When
size() > capacity
, the eldest entry (least recently used) is automatically removed. - No external cleanup logic is needed — the cache manages itself! 🧠
🧠 TL;DR
Feature | With LinkedHashMap |
---|---|
Keep access order | new LinkedHashMap(cap, 0.75f, true) |
Define eviction policy | Override removeEldestEntry(...) |
Auto-eviction (e.g. LRU) | ✅ Built-in with small subclass |