Skip to content

Commit 32bafcd

Browse files
Create IdentityHashMapDemo.java
1 parent 18b9f3c commit 32bafcd

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package learnCollections;
2+
3+
import java.util.HashMap;
4+
import java.util.IdentityHashMap;
5+
import java.util.Map;
6+
7+
public class IdentityHashMapDemo {
8+
public static void main(String[] args) {
9+
String key1 = new String("key");
10+
String key2 = new String("key");
11+
12+
Map<String, Integer> map = new HashMap<>();
13+
// hashcode and equals
14+
map.put(key1, 1); // hashcode1 --> index1
15+
map.put(key2, 2); // hashcode1 --> index1 --> equals() --> replace value of key with 2
16+
System.out.println(key1.equals(key2));
17+
System.out.println(map);
18+
19+
20+
// whether the class has overridden equals() and hashCode() or not, in IdentityHashMap, object class hashcode will be used which is based on memory address
21+
// hence object hashcode will be considered for key1 and key2, which will be different
22+
Map<String, Integer> identityMap = new IdentityHashMap<>();
23+
System.out.println(System.identityHashCode(key1)); // 292938459
24+
System.out.println(System.identityHashCode(key2)); // 917142466
25+
26+
System.out.println(key1.hashCode()); // 106079
27+
System.out.println(key2.hashCode()); // 106079
28+
29+
// IdentityHashcode and ==
30+
identityMap.put(key1, 1); // key1 --> index1
31+
identityMap.put(key2, 2); // key2 --> index2 (different from key1)
32+
System.out.println(identityMap); // {key=2, key=1}
33+
}
34+
}

0 commit comments

Comments
 (0)