Skip to content

Commit b28fa8e

Browse files
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

1 file changed

+1
-0
lines changed

Section 25 Collections Frameworks/Map Interface/Linked HashMap/src/LinkedHashMapDemo1.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
public class LinkedHashMapDemo1 {
66
public static void main(String[] args) {
77
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
8+
89
// But it maintains order.
910
linkedHashMap.put("Orange",10);
1011
linkedHashMap.put("Apple",20);

0 commit comments

Comments
 (0)