## Basic storage logic of HashMap

Lawrence 2020-11-10 17:23:53
basic storage logic hashmap

HashMap Is based on `hashing` Principle , We can go through put() and get() Method to store and retrieve objects . When we pass the key-value pair to put() When the method is used , It calculates and gets the bond's hash value （ And further get the index position ）, obtain Map Index position in array , Determine whether there are elements in the position ,
1、 If it doesn't exist, a new one will be created ,
2、 Otherwise, judge the current node's key If it is the same as the deposit, it will be obtained node Used for replacement value
3、 Of this node key Different , The traverse ：
If the node is not a linked list but a red black tree, then traverse the tree （ When the value of the list exceeds 8 It will turn into a red and black tree ）
If the node is a linked list

``````if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// The total length of the current array -1 and hash Values and operations calculate the index position
if ((p = tab[i = (n - 1) & hash]) == null)
// Recreate a node , Last parameter null, The node has only one storage object
else {
Node<K,V> e; K k;
// Otherwise, judge the current node's key Is it the same as the deposit
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// If there is the same key The replacement
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}``````

jdk 1.8 Add the red black tree village structure , namely When the length of the linked list corresponding to an array node is greater than 8 when , It will be automatically converted to red and black output storage , When the value of the list is less than 6 Then it will return to the list from the red and black tree To improve efficiency 