Commit f4299ce
committed
feat(LRUCacheDemo): implement simple LRU cache using LinkedHashMap
What
- Added generic `LRUCacheDemo<K, V>` class extending LinkedHashMap.
- Configured `accessOrder=true` to reorder entries based on usage.
- Overrode `removeEldestEntry()` to evict least recently used element when capacity exceeded.
- Added a demo in `main()` with a student marks example.
Why
- Demonstrates how LinkedHashMap can be leveraged to build an **LRU cache** with minimal code.
- Useful for scenarios like caching results, database lookups, or frequently accessed data with limited memory.
How
- Constructor sets custom capacity and calls super with access-order enabled.
- Each `put()` or `get()` operation moves the accessed key to the end of the order.
- When size > capacity, the eldest (least recently used) entry is evicted automatically.
- Demo: inserted 5 student entries with capacity = 3 to illustrate eviction.
Logic
1. Insert "Bob", "Alice", "Ram" → cache full: ["Bob", "Alice", "Ram"]
2. Update "Bob" → reorders to most recent: ["Alice", "Ram", "Bob"]
3. Insert "Vipul" → capacity exceeded → removes eldest ("Alice"): ["Ram", "Bob", "Vipul"]
Real-life applications
- Browser history or session caching.
- Database query result cache.
- Image/object caching in web apps or mobile apps.
- Any system where **least recently used** data should be automatically discarded.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent e1813d5 commit f4299ce
File tree
1 file changed
+6
-7
lines changed- Section 25 Collections Frameworks/Map Interface/Linked HashMap/LRU Cache/src
1 file changed
+6
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | 3 | | |
6 | | - | |
| 4 | + | |
7 | 5 | | |
8 | 6 | | |
9 | | - | |
| 7 | + | |
10 | 8 | | |
11 | 9 | | |
12 | 10 | | |
| |||
17 | 15 | | |
18 | 16 | | |
19 | 17 | | |
20 | | - | |
| 18 | + | |
| 19 | + | |
21 | 20 | | |
22 | 21 | | |
23 | 22 | | |
| |||
27 | 26 | | |
28 | 27 | | |
29 | 28 | | |
30 | | - | |
31 | | - | |
| 29 | + | |
| 30 | + | |
32 | 31 | | |
33 | 32 | | |
34 | 33 | | |
| |||
0 commit comments