在java中HashMap作為一種Map的實現,在程序中我們經常會用到,在此記錄下其中get與put的執行過程,以及其hash沖突的解決方式:
HashMap在存儲數據的時候是key-value的鍵值對的形式存放的,一個key-value會創建一個Map.Entry實現類,在HashMap中該實現類分為Node和TreeNode,其中TreeNode繼承了Node類,在沒有hash沖突的情況下,這些Map.Entry實現類會組成數組table存放。key的hashCode值決定了該Map.Entry在table中的索引
HashMap的hash算法是key的hashCode異或key的hashCode無符號右移16位
在放入key到一定程度的時候就會出現不同的key值運算出相同的hash值,導致多個Map.Entry類存放在table同一個索引位置上,這個時候就是所謂的hash沖突。
通過觀察put(key,value)方法:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; 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 (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
我們發現,在執行過程中會首先取出table在(table.length-1)&hash(key)的值,如果該值為空,說明還沒有發生hash沖突,直接new一個Node放在該索引處,
如果該值不為空,說明已經存放過相同hash值的key,繼續判斷兩個key的equals方法是否相等,如果相等則覆蓋原來的值。如果不等,則出現hash沖突。
在出現hash沖突時首先會判斷當前的Node是否是TreeNode,如果是TreeNode則在該TreeNode上添加一個分支。如果不是,那么說明是Node類。在table中只會存在這兩個Map.Entry實現類。在所有的Node都有一個next變量,當出現hash沖突時,就會將該Node的next變量賦值為要放入的新的Node,這樣在多次沖突后該位置就會形成一個類似於鏈表的結構,當該鏈表長度為8時,為了提高性能,就會將該鏈表替換成樹結構的TreeNode。
以上就是HashMap解決hash沖突的方式。
當調用get方法時
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; }
會通過key的hash值獲取table中的Node,並通過key的equals方法來確定要取的Node,在返回Node的value值。
通過HashMap的存儲結構可以發現當我們遍歷HashMap時通過entrySet方法性能會高一點,因為它直接返回了存儲的Map.Entry類,而遍歷key方式是通過遍歷Map.Entry取出key,我們在調用get(key)方法時又會去取一次Entry,所以性能會比較低