Skip to content

Commit 7cf47c8

Browse files
committed
feat(IdentityHashMapDemo3): demonstrate reference equality in IdentityHashMap
What - Added IdentityHashMapDemo3 class. - Shows how IdentityHashMap compares keys using `==` (reference equality) instead of `.equals()`. - Inserted two different String objects (`new String("key")`) with same content. - Printed map contents and result of `key1.equals(key2)`. Why - To highlight the core difference between HashMap and IdentityHashMap. - Reinforces that IdentityHashMap treats distinct object references as unique keys even if their contents are equal. - Useful for scenarios where object identity (not value equality) should determine uniqueness. How - Created key1 and key2 with `new String("key")` to guarantee different references. - map.put(key1,1) followed by map.put(key2,2). - IdentityHashMap uses reference check → stores both entries. - Printed results to show both entries are preserved and equals() returns true. Logic - Inputs: - Two distinct String objects with identical characters. - Processing: - IdentityHashMap checks (k1 == k2). - Since key1 != key2 (different references), both are stored as separate entries. - Outputs: - IdentityHashMap contains two entries: `{key=1, key=2}` (order unspecified). - `key1.equals(key2)` prints `true`. Real-life applications - Useful in frameworks or caches where identity, not logical equality, defines uniqueness. - Common in serialization frameworks, proxy handling, or object graph traversal where distinct references matter. Signed-off-by: https://github.com/Someshdiwan <someshdiwan369@gmail.com>
1 parent 23d5798 commit 7cf47c8

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.IdentityHashMap;
2+
import java.util.Map;
3+
4+
public class IdentityHashMapDemo3 {
5+
public static void main(String[] args) {
6+
// Two different String objects but with same content "key"
7+
String key1 = new String("key");
8+
String key2 = new String("key");
9+
10+
// IdentityHashMap → uses reference equality (==)
11+
Map<String, Integer> map = new IdentityHashMap<>();
12+
13+
map.put(key1, 1); // First insert
14+
map.put(key2, 2); // Stored separately because key1 != key2 (different objects)
15+
16+
System.out.println("IdentityHashMap Result: " + map);
17+
18+
System.out.println(key1.equals(key2));
19+
}
20+
}
21+
22+
// Using IdentityHashMap (uses == reference comparison).
23+
24+
/* Difference Recap:
25+
• HashMap → merges both keys because key1.equals(key2) → true.
26+
27+
• IdentityHashMap → keeps both entries because key1 == key2 → false.
28+
*/

0 commit comments

Comments
 (0)