Commit b28fa8e
committed
feat(LinkedHashMapDemo1): compare ordering behavior of LinkedHashMap vs HashMap
What
- Added LinkedHashMapDemo1 class.
- Inserted the same key-value pairs ("Orange",10), ("Apple",20), ("Guava",13) into both a LinkedHashMap and a HashMap.
- Iterated over each map and printed entries to highlight ordering differences.
Why
- To demonstrate that LinkedHashMap preserves insertion order, while HashMap does not guarantee any order.
- Clarifies a common misconception for beginners that both behave the same.
- Helps developers choose the correct map type when predictable iteration order is required.
How
- Created linkedHashMap and inserted three entries in order.
- Iterated via entrySet() and printed results → preserves insertion sequence.
- Created hashMap with same entries.
- Iterated via entrySet() → order may vary depending on hash distribution.
- Added explanatory comments for clarity.
Logic
- Inputs: three string keys with integer values.
- Processing:
- LinkedHashMap internally uses a doubly-linked list along with buckets → preserves insertion order.
- HashMap uses hashing only → iteration order is bucket-dependent, not predictable.
- Outputs:
- LinkedHashMap → prints exactly in the order of insertion: Orange, Apple, Guava.
- HashMap → may print in different order, e.g., {Guava, Orange, Apple}.
Real-life applications
- Use LinkedHashMap when insertion order matters (e.g., displaying data in consistent order).
- Use HashMap when only key lookup speed matters and ordering is irrelevant.
- Use LinkedHashMap with accessOrder=true for LRU cache implementations.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent c9f9e3d commit b28fa8e
File tree
1 file changed
+1
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Linked HashMap/src
1 file changed
+1
-0
lines changedLines changed: 1 addition & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
5 | 5 | | |
6 | 6 | | |
7 | 7 | | |
| 8 | + | |
8 | 9 | | |
9 | 10 | | |
10 | 11 | | |
| |||
0 commit comments