Commit 7cf47c8
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
- Section 25 Collections Frameworks/Map Interface/Identity HashMap/src
Lines changed: 28 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 | + | |
0 commit comments