### Hashmap在JDK8中的提升

HashMap使用key的hashCode()和equals()方法來將值划分到不同的桶里。

`//鏈表節點static class Node<K,V> implements Map.Entry<K,V> {        final int hash;        final K key;        V value;        Node<K,V> 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);        }        //省略  }// HashMap的主要屬性public class HashMap<K,V> extends AbstractMap<K,V>    implements Map<K,V>, Cloneable, Serializable {    // 槽數組。Node<K,V>類型。TreeNode extends LinkedHashMap.Entry<K,V>，所以能夠存放TreeNode來實現Tree bins    transient Node<K,V>[] table;        transient Set<Map.Entry<K,V>> entrySet;    transient int size;    // 去掉了volatile的修飾符    transient int modCount;    int threshold;    final float loadFactor;    ...}`
`//計算key的hashstatic final int hash(Object key) {        int h;        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }`

`public V get(Object key) {        Node<K,V> e;        return (e = getNode(hash(key), key)) == null ? null : e.value;    }     final Node<K,V> getNode(int hash, Object key) {            Node<K,V>[] tab;             Node<K,V> first, e;             int n; K k;            //hash & length-1 定位數組下標            if ((tab = table) != null && (n = tab.length) > 0 &&                (first = tab[(n - 1) & hash]) != null)             {                if (first.hash == hash && // always check first node                    ((k = first.key) == key || (key != null && key.equals(k))))                    return first;                if ((e = first.next) != null) {                    /*第一個節點是TreeNode,則採用位桶+紅黑樹結構，                     * 調用TreeNode.getTreeNode(hash,key),                     *遍歷紅黑樹。得到節點的value                     */                    if (first instanceof TreeNode)                        return ((TreeNode<K,V>)first).getTreeNode(hash, key);                    do {                        if (e.hash == hash &&                            ((k = e.key) == key || (key != null && key.equals(k))))                            return e;                       } while ((e = e.next) != null);                }            }            return null;        }     final TreeNode<K,V> getTreeNode(int h, Object k) {             //找到紅黑樹的根節點並遍歷紅黑樹         return ((parent != null) ? root() : this).find(h, k, null);     }     /*      *通過hash值的比較，遞歸的去遍歷紅黑樹，這里要提的是compareableClassFor(Class k)這個函數的作用。在某些時候      *假設紅黑樹節點的元素are of the same "class C implements Comparable<C>" type       *利用他們的compareTo()方法來比較大小，這里須要通過反射機制來check他們究竟是不是屬於同一個類,是不是具有可比較性.      */     final TreeNode<K,V> find(int h, Object k, Class<?> kc) {         TreeNode<K,V> p = this;         do {             int ph, dir; K pk;             TreeNode<K,V> pl = p.left, pr = p.right, q;             if ((ph = p.hash) > h)                 p = pl;             else if (ph < h)                 p = pr;             else if ((pk = p.key) == k || (k != null && k.equals(pk)))                 return p;             else if (pl == null)                 p = pr;             else if (pr == null)                 p = pl;             else if ((kc != null ||                       (kc = comparableClassFor(k)) != null) &&                      (dir = compareComparables(kc, k, pk)) != 0)                 p = (dir < 0) ? pl : pr;             else if ((q = pr.find(h, k, kc)) != null)                 return q;             else                 p = pl;         } while (p != null);         return null;     }`

`//put(K key,V value)函數     public V put(K key, V value) {            return putVal(hash(key), key, value, false, true);        }        final V putVal(int hash, K key, V value, boolean onlyIfAbsent,            boolean evict) {         Node<K,V>[] tab;          Node<K,V> p;          int n, i;         //假設table為空或者長度為0，則resize()         if ((tab = table) == null || (n = tab.length) == 0)             n = (tab = resize()).length;         //找到key值相應的槽而且是第一個，直接增加         if ((p = tab[i = (n - 1) & hash]) == null)             tab[i] = newNode(hash, key, value, null);         else {                 Node<K,V> e;                 K k;                 //第一個node的hash值即為要增加元素的hash                 if (p.hash == hash &&                     ((k = p.key) == key || (key != null && key.equals(k)))){                      e = p;                 }else if (p instanceof TreeNode)//第一個節點是TreeNode，即tree-bin                    /*Tree version of putVal.                     *final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,int h, K k, V v)                     */                     e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);                     else {                         //不是TreeNode,即為鏈表,遍歷鏈表                         for (int binCount = 0; ; ++binCount) {                             /*到達鏈表的尾端也沒有找到key值同樣的節點，                              *則生成一個新的Node,而且推斷鏈表的節點個數是不是到達轉換成紅黑樹的上界                              *達到。則轉換成紅黑樹                              */                             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);                     //返回舊的value值                     return oldValue;                 }         }         ++modCount;         if (++size > threshold)             resize();         afterNodeInsertion(evict);         return null;}`

HashMap會動態的使用一個專門的treemap實現來替換掉它。

JDK 8中從O(n)到O(logn)的飛躍，能夠有效地防止類似的攻擊，同一時候也讓HashMap性能的可預測性略微增強了一些。