Commit f103162
committed
feat(HashMapOrderDemo): illustrate non-deterministic iteration order in HashMap
What
- Added HashMapOrderDemo class.
- Demonstrated basic HashMap operations:
- put() to insert/update entries.
- getOrDefault() for safe retrieval.
- Printed the map contents to show iteration order.
- Added detailed comments explaining why HashMap does not preserve insertion order.
Why
- To highlight that HashMap does not guarantee ordering of keys or entries.
- Developers often mistakenly assume insertion order is preserved.
- Provides guidance on when to use LinkedHashMap or TreeMap instead.
How
- Created a HashMap<String, Integer>.
- Inserted three entries: ("Shubham", 91), ("Bob", 80), ("Akshit", 78).
- Retrieved non-existing key with getOrDefault("Vipul", 0).
- Updated "Shubham" to new value 92.
- Printed the HashMap to observe output order.
Logic
- Inputs: string keys and integer scores.
- Processing:
- HashMap places entries into internal buckets using hashCode().
- Iteration traverses buckets, not insertion sequence.
- Outputs:
- Map print shows contents in an arbitrary, non-guaranteed order.
- Example: {Akshit=78, Shubham=92, Bob=80} but actual order may differ.
Real-life applications
- HashMap → use when you need fast key-based lookups and order doesn’t matter.
- LinkedHashMap → use when insertion order or access-order must be preserved.
- TreeMap → use when you need keys sorted by natural ordering or a custom Comparator.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 30c9b64 commit f103162
File tree
1 file changed
+46
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Linked HashMap/src
1 file changed
+46
-0
lines changedLines changed: 46 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
0 commit comments