Commit c9f9e3d
committed
feat(LinkedHashMapDemo): demonstrate insertion, access order, and iteration in LinkedHashMap
What
- Added LinkedHashMapDemo class.
- Constructed a LinkedHashMap with parameters `(5, 0.75F, true)`:
- initial capacity = 5
- load factor = 0.75
- accessOrder = true (entries reorder on access).
- Inserted seven key-value pairs with integer keys and string values.
- Accessed keys 2, 5, and 1 using get().
- Iterated with forEach() to print the order.
Why
- To show how LinkedHashMap behaves with access-order enabled.
- Demonstrates that most recently accessed entries are moved to the end of the iteration order.
- Helps explain its relevance for caching strategies like LRU.
How
- Populated LHM with multiple entries.
- Called get(2), get(5), and get(1) to simulate access.
- Iterated with LHM.forEach((k,v) -> …) to display access-order iteration.
Logic
- Inputs:
- Integer keys 1–7 with string messages as values.
- Processing:
- LinkedHashMap maintains a doubly-linked list of entries.
- With accessOrder=true, each access (get/put) moves the entry to the tail.
- Outputs:
- Printed iteration order shows least recently accessed entries first, most recently accessed last.
Real-life applications
- LinkedHashMap with access-order is a foundation for implementing LRU caches:
- Override `removeEldestEntry()` to automatically evict oldest entries when a size limit is exceeded.
- Useful in memory-sensitive apps, caching layers, and session management.
- Compared:
- HashMap → no order guarantee.
- LinkedHashMap (default) → preserves insertion order.
- LinkedHashMap (accessOrder=true) → preserves access order.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 89d2b06 commit c9f9e3d
File tree
1 file changed
+11
-14
lines changed- Section 25 Collections Frameworks/Map Interface/Linked HashMap/src
1 file changed
+11
-14
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 | | - | |
11 | | - | |
| 8 | + | |
12 | 9 | | |
13 | 10 | | |
14 | 11 | | |
15 | | - | |
16 | | - | |
| 12 | + | |
| 13 | + | |
17 | 14 | | |
18 | 15 | | |
19 | 16 | | |
| |||
23 | 20 | | |
24 | 21 | | |
25 | 22 | | |
26 | | - | |
| 23 | + | |
27 | 24 | | |
28 | | - | |
29 | | - | |
| 25 | + | |
30 | 26 | | |
31 | 27 | | |
32 | 28 | | |
33 | 29 | | |
34 | 30 | | |
35 | | - | |
36 | | - | |
37 | | - | |
38 | | - | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
0 commit comments