8000 add a HashMap example · fishercoder1534/RandomJava@252bae4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 252bae4

Browse files
add a HashMap example
1 parent 8332304 commit 252bae4

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/main/java/hashmap/MainApp.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package hashmap;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class MainApp {
7+
private static final int NUMBER_OF_MAP_ENTRIES = 2;
8+
9+
public static void main(String... args) {
10+
System.out.println("Program started.");
11+
MainApp mainApp = new MainApp();
12+
mainApp.understandHashMapInternalWorkings();
13+
System.out.println("Program finished.");
14+
}
15+
16+
private void understandHashMapInternalWorkings() {
17+
/**This arcitle says it pretty well: https://levelup.gitconnected.com/internal-working-of-hashmap-in-java-latest-updated-4c2708f76d2c
18+
* 1. HashMap uses its static inner class Node<K,V> for storing map entries. That means each entry in hashMap is a Node.
19+
* 2. Internally HashMap uses a hashCode of the key Object and this hashCode is further used by the hash function to find the index of the bucket where the new entry can be added.
20+
* 3. HashMap uses multiple buckets and each bucket points to a Singly Linked List where the entries (nodes) are stored.
21+
* 4. Once the bucket is identified by the hash function using hashcode, then hashCode is used to check if there is already a key with the same hashCode or not in the bucket (I mean corresponding singly linked list).
22+
* If there already exists a key with the same hashCode, then the equals() method is used on the keys.
23+
* If the equals method returns true, that means there is already a node with the same key and hence the value against that key is overwritten in the entry (node),
24+
* otherwise, a new node is created and added to this Singly Linked List of that bucket.
25+
* If there is no key with the same hashCode in the bucket found by the hash function then the new Node is added to the bucket found.
26+
* 5. There's a threshold after which is reached, HashMap will change from using singly linked list to use a self-balancing BST, static final int TREEIFY_THRESHOLD = 8;
27+
* the motive for this change is that it could take O(n) worst case for look up with linked list, however, with a self-balancing BST, e.g. red-black tree, we could get O(logn) lookup time;
28+
*
29+
* To have a high-performance hashMap we need good implementation of hashCode() and equals() method along with hash function.
30+
* */
31+
Map<String, String> map = new HashMap<>();
32+
for (int i = 0; i < NUMBER_OF_MAP_ENTRIES; i++) {
33+
map.put("key" + i, "value" + i);
34+
}
35+
map.put("key1", "value_new");
36+
System.out.println("this method finishes.");
37+
}
38+
}

0 commit comments

Comments
 (0)
0