Commit caa4482
committed
feat(LinkedHashMapDemo3): demonstrate size-limited LinkedHashMap with removeEldestEntry
What
- Added LinkedHashMapDemo3 class.
- Created an anonymous subclass of LinkedHashMap overriding `removeEldestEntry`.
- Enforced automatic eviction of the eldest entry when map size exceeds 7.
- Inserted multiple entries and accessed some keys to show access-order behavior.
- Printed final contents to illustrate automatic removal.
Why
- To demonstrate how LinkedHashMap can be customized to function as a bounded cache (like LRU cache).
- Shows the real-world use case of `removeEldestEntry()` for controlling map size.
- Useful for scenarios where memory needs to be managed automatically (e.g., caching recently used items).
How
- Constructed LinkedHashMap with `accessOrder=true` to maintain order based on recent access.
- Overrode `removeEldestEntry` to return true when `size() > 7`, ensuring eviction policy.
- Added 8 entries, with key `8` triggering removal of the least recently accessed element.
- Accessed keys `2`, `5`, and `1` before inserting `8` to reorder usage.
- Iterated with forEach to display results.
Logic
- Input: put 8 entries into a LinkedHashMap with max size 7.
- Processing: `removeEldestEntry` checks if size > 7 → removes eldest entry automatically.
- Because `accessOrder=true`, "eldest" is defined by least recent access, not oldest insertion.
- Output: final map contains 7 entries (key 8 present, one least accessed entry removed).
Real-life applications
- Implementing **LRU (Least Recently Used) caches** in memory-sensitive apps.
- Bounded-size maps where stale entries should be discarded automatically.
- Frequently used in frameworks like Spring, Hibernate, or custom cache implementations.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent b28fa8e commit caa4482
File tree
1 file changed
+8
-13
lines changed- Section 25 Collections Frameworks/Map Interface/Linked HashMap/src
1 file changed
+8
-13
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | 3 | | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
| 4 | + | |
| 5 | + | |
10 | 6 | | |
11 | | - | |
12 | | - | |
| 7 | + | |
13 | 8 | | |
14 | | - | |
15 | | - | |
| 9 | + | |
16 | 10 | | |
17 | 11 | | |
18 | 12 | | |
19 | 13 | | |
20 | 14 | | |
21 | | - | |
22 | | - | |
| 15 | + | |
| 16 | + | |
23 | 17 | | |
24 | 18 | | |
25 | 19 | | |
| |||
30 | 24 | | |
31 | 25 | | |
32 | 26 | | |
| 27 | + | |
33 | 28 | | |
34 | 29 | | |
35 | 30 | | |
36 | 31 | | |
37 | 32 | | |
38 | | - | |
| 33 | + | |
0 commit comments