HashMap是咱們最經常使用的集合之一,同時Java8也提高了HashMap的性能。本着學習的原則,在這探討一下HashMap。html
簡單講解下HashMap的原理:HashMap基於Hash算法,咱們經過put(key,value)存儲,get(key)來獲取。當傳入key時,HashMap會根據key.hashCode()計算出hash值,根據hash值將value保存在bucket裏。當計算出的hash值相同時怎麼辦呢,咱們稱之爲Hash衝突,HashMap的作法是用鏈表和紅黑樹存儲相同hash值的value。當Hash衝突的個數比較少時,使用鏈表,不然使用紅黑樹。java
一圖勝千言:node
咱們能夠在HashMap的源碼中找到這樣一句:算法
transient Node<K,V>[] table;
很明顯,HashMap仍是憑藉數組實現的,輔以鏈表和紅黑樹。咱們知道數組的特色:尋址容易,插入和刪除困難,而鏈表的特色是:尋址困難,插入和刪除容易,紅黑樹則對插入時間、刪除時間和查找時間提供了最好可能的最壞狀況擔保。HashpMap將這三者結合在一塊兒。api
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
若是你也看過7以前的Hash算法,會發現這個版本的算法比以前的簡潔。數組
static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } }
鏈表節點,存儲鍵值對,並含有一個next引用。數據結構
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } /** * Returns root of tree containing this node. */ final TreeNode<K,V> root() { for (TreeNode<K,V> r = this, p;;) { if ((p = r.parent) == null) return r; r = p; } } /** * Ensures that the given root is the first node of its bin. */ static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) { int n; if (root != null && tab != null && (n = tab.length) > 0) { int index = (n - 1) & root.hash; TreeNode<K,V> first = (TreeNode<K,V>)tab[index]; if (root != first) { Node<K,V> rn; tab[index] = root; TreeNode<K,V> rp = root.prev; if ((rn = root.next) != null) ((TreeNode<K,V>)rn).prev = rp; if (rp != null) rp.next = rn; if (first != null) first.prev = root; root.next = first; root.prev = null; } assert checkInvariants(root); } }
紅黑樹的節點app
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; }
這是HashMap中的put函數,裏面的參數boolean onlyIfAbsent,boolean evict我並不知道有什麼用,由於put在調用的時候,是將這兩個參數寫死了,若知道請告知:函數
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
另外咱們能夠看到,當節點個數>= TREEIFY_THRESHOLD - 1時,HashMap將採用紅黑樹存儲。爲何這麼作呢?正如咱們前面提到的,當發生Hash衝突時,HashMap首先是採用鏈表將重複的值串起來,並將最後放入的值置於鏈首,java8對HashMap進行了優化。當節點個數多了以後使用紅黑樹存儲。這樣作的好處是,最壞的狀況下即全部的key都Hash衝突,採用鏈表的話查找時間爲O(n),而採用紅黑樹爲O(logn),這也是Java8中HashMap性能提高的奧祕,詳細的測試能夠看這篇博文。性能
這篇文章簡單介紹了下Java8中的HashMap中的數據結構,Hash算法,內部類,簡單分析了Java8中性能提高的奧祕,因爲水平緣由不免會出現一些紕漏,但願各位能即時糾正。