天天看點

JDK源碼閱讀之集合篇-HashMap(2)1.完成目标

 接上篇。注意:這裡HashMap是使用的JDK8的版本。

1.完成目标

1)HashMap的資料結構和存儲結構

 HashMap使用了“數組+連結清單+紅黑樹”的資料結構。

 存儲結構如下圖所示:

JDK源碼閱讀之集合篇-HashMap(2)1.完成目标

HashMap采用了(數組+連結清單+紅黑樹)的複雜結構,數組中的每一個元素又稱作桶(bin)。

當一個桶中元素個數達到8個,并且桶的個數達到64時,則将這個桶中的連結清單轉化為一顆紅黑樹。

2)HashMap中主要的屬性、主要方法的實作過程

主要屬性:

/**
     * 數組,桶(bins)數組
     */
    transient Node<K,V>[] table;

    /**
     * 條目集
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * 元素的數量,即桶的個數
     */
    transient int size;

    /**
     * 修改次數,用于在疊代的時候執行快速失敗政策
     */
    transient int modCount;

    /**
     * 門檻值,表示當桶的數量達到多少時進行擴容,threshold=capacity * loadFactor
     */
    int threshold;

    /**
     * 裝載因子
     */
    final float loadFactor;
           

兩個特殊的資料結構:

Node内部類

Node是一個典型的單連結清單節點,其中,hash用來存儲key計算得來的hash值。

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
}
           

TreeNode内部類

這是一個神奇的類,它繼承自LinkedHashMap中的Entry類,關于LInkedHashMap.Entry這個類我們後面再講。

TreeNode是一個典型的樹型節點,其中,prev是連結清單中的節點,用于在删除元素的時候可以快速找到它的前置節點。

// 位于HashMap中 
    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;
    }

    // 位于LinkedHashMap中,典型的雙向連結清單節點
    static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }
           

主要方法及其實作過程:

1.構造方法

 一共有3個構造方法。

/**
    * 使用預設值構造一個空的HashMap
   */
   public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; 
   }
   
   /**
     * 調用HashMap(int initialCapacity, float loadFactor)構造方法,傳入預設裝載因子
    */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
   
   /**
   * 判斷傳入的初始容量和裝載因子是否合法,并計算擴容門檻,擴容門檻為傳入的初始容量往上取最近的
   * 2的n次方
   */
   public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    

    
           

tableSizeFor(int cap)方法

/**
     * 傳回傳入容量參數的向上取最近的2的n次方
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
           

2.添加元素方法put(K key, V value)

/**
     * 通過hash()函數計算key的hash值,然後調用putVal()執行添加元素
    */
    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;
        //如果桶數組為空或者桶的大小為0,則先調用resize()進行擴容操作
        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 {
                //否則,周遊這個連結清單,在表中查找key=目标元素key的節點
                for (int binCount = 0; ; ++binCount) {
                    //如果直到連結清單尾都沒有找到該key=目标元素key的節點,則執行插入操作
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //當執行完插入操作後,如果連結清單節點數>=8時,則轉化為紅黑樹(樹化),這裡減一是因為開始的節點沒有統計到binCount中
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果找到key=目标元素key的節點
                    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;
                //回調接口,在LinkedHashMap中用到
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //到這裡了說明沒有找到元素
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
           

(1)通過hash()函數計算key的hash值,然後調用putVal()執行添加元素

(2)如果桶數組為空或者桶的大小為0,則先調用resize()進行擴容操作

(3)判斷目标位置的桶是否為空,如果為空,則直接将節點插入這個桶中

(4)判斷第一個節點是否是要找的節點

(5)判斷第一個節點是否是樹節點,如果是,則在紅黑樹中執行添加元素的操作

(6)如果前兩種情況都不滿足,則在連結清單中執行添加元素的操作

(7)如果找到了對應key的元素,則判斷是否需要替換舊值,并直接傳回舊值

(8)如果插入了元素,則數量加1并判斷是否需要擴容

擴容方法resize()

/**
    * 初始化桶數組或者容量加倍
    */
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            // 如果桶數組的容量已經達到最大容量2^30就不再增大
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 否則,桶容量和桶容量門檻值加倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        // 如果舊的桶數組不空,則開始遷移元素操作
        if (oldTab != null) {
            // 循環周遊每一個桶數組元素
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    // 如果是該桶數組元素中隻有一個節點,則直接進行遷移
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    // 如果該節點是樹節點,則需要進行相應的切分,将一顆樹打散到兩顆樹到新桶中
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
           

TreeNode.putTreeVal(…)方法

将元素插入到紅黑樹中的方法。

final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K,V> root = (parent != null) ? root() : this;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }
           

(1)尋找根節點;

(2)從根節點開始查找;

(3)比較hash值及key值,如果都相同,直接傳回,在putVal()方法中決定是否要替換value值;

(4)根據hash值及key值确定在樹的左子樹還是右子樹查找,找到了直接傳回;

(5)如果最後沒有找到則在樹的相應位置插入元素,并做平衡;

treeifyBin()方法

如果插入元素後連結清單的長度大于等于8則判斷是否需要樹化。

/**
    * 将連結清單進行樹化
    */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 如果桶數組為空或者桶數組的長度小于64則隻進行擴容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                // 周遊,将連結清單中的節點替換為樹節點
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            // 替換完成後,從頭節點開始樹化
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }
           

TreeNode.treeify()方法

真正樹化的方法。

final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                // 第一個元素作為根節點且為黑節點,其它元素依次插入到樹中再做平衡
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    // 從根節點查找元素插入的位置
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);
                        // 如果最後沒找到元素,則插入
                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            // 插入後平衡,預設插入的是紅節點,在balanceInsertion()方法裡
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            // 把根節點移動到連結清單的頭節點,因為經過平衡之後原來的第一個元素不一定是根節點了
            moveRootToFront(tab, root);
        }
           

(1)從連結清單的第一個元素開始周遊

(2)将第一個元素作為根節點

(3)其它元素依次插入到紅黑樹中,再做平衡

(4)将根節點移到連結清單第一進制素的位置(因為平衡的時候根節點會改變)

3.根據key取得元素方法get(Object key)

public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * Implements Map.get and related methods
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        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) {
                // 如果第一個節點是樹節點,則在樹節點中執行查找
                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;
    }
           

1.首先通過計算hash(key)得到桶的位置

2.判斷桶的第一個節點是不是目标節點,如果是,則直接傳回

3.如果不是,則判斷第一個節點是不是樹節點,如果是,則在樹節點中執行查找

4.否則,周遊連結清單節點,進行查找

TreeNode.getTreeNode(int h, Object k)方法

final TreeNode<K,V> getTreeNode(int h, Object k) {
            // 從樹的根節點開始查找
            return ((parent != null) ? root() : this).find(h, k, null);
        }

        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)
                    // hash相同但key不同,左子樹為空查右子樹
                    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;
        }
           

經典二叉查找樹的查找過程,先根據hash值比較,再根據key值比較決定是查左子樹還是右子樹。

4.根據key删除元素方法remove(Object key)

public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        // 如果對應的桶數組不為空,則在該桶數組元素中尋找滿足key=要删除的key的節點
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            // 如果是第一個節點
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                // 如果是樹節點
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                // 如果是連結清單節點
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            // 如果找到了
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                // 如果是樹節點
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                // 如果是連結清單的第一個節點
                else if (node == p)
                    tab[index] = node.next;
                // 如果是連結清單中剩下的其他節點
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }
           

(1)先查找元素所在的節點

(2)如果找到的節點是樹節點,則按樹的移除節點處理

(3)如果找到的節點是桶中的第一個節點,則把第二個節點移到第一的位置

(4)否則按連結清單删除節點處理

(5)修改size,調用移除節點後置處理等

TreeNode.removeTreeNode(…)方法

final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
                                  boolean movable) {
            int n;
            if (tab == null || (n = tab.length) == 0)
                return;
            int index = (n - 1) & hash;
            TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
            TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
            if (pred == null)
                tab[index] = first = succ;
            else
                pred.next = succ;
            if (succ != null)
                succ.prev = pred;
            if (first == null)
                return;
            if (root.parent != null)
                root = root.root();
            if (root == null || root.right == null ||
                (rl = root.left) == null || rl.left == null) {
                tab[index] = first.untreeify(map);  // too small
                return;
            }
            TreeNode<K,V> p = this, pl = left, pr = right, replacement;
            if (pl != null && pr != null) {
                TreeNode<K,V> s = pr, sl;
                while ((sl = s.left) != null) // find successor
                    s = sl;
                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
                TreeNode<K,V> sr = s.right;
                TreeNode<K,V> pp = p.parent;
                if (s == pr) { // p was s's direct parent
                    p.parent = s;
                    s.right = p;
                }
                else {
                    TreeNode<K,V> sp = s.parent;
                    if ((p.parent = sp) != null) {
                        if (s == sp.left)
                            sp.left = p;
                        else
                            sp.right = p;
                    }
                    if ((s.right = pr) != null)
                        pr.parent = s;
                }
                p.left = null;
                if ((p.right = sr) != null)
                    sr.parent = p;
                if ((s.left = pl) != null)
                    pl.parent = s;
                if ((s.parent = pp) == null)
                    root = s;
                else if (p == pp.left)
                    pp.left = s;
                else
                    pp.right = s;
                if (sr != null)
                    replacement = sr;
                else
                    replacement = p;
            }
            else if (pl != null)
                replacement = pl;
            else if (pr != null)
                replacement = pr;
            else
                replacement = p;
            if (replacement != p) {
                TreeNode<K,V> pp = replacement.parent = p.parent;
                if (pp == null)
                    root = replacement;
                else if (p == pp.left)
                    pp.left = replacement;
                else
                    pp.right = replacement;
                p.left = p.right = p.parent = null;
            }

            TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

            if (replacement == p) {  // detach
                TreeNode<K,V> pp = p.parent;
                p.parent = null;
                if (pp != null) {
                    if (p == pp.left)
                        pp.left = null;
                    else if (p == pp.right)
                        pp.right = null;
                }
            }
            if (movable)
                moveRootToFront(tab, r);
        }
           

(1)TreeNode本身既是連結清單節點也是紅黑樹節點

(2)先删除連結清單節點

(3)再删除紅黑樹節點并做平衡

總結

(1)HashMap是一種散清單,采用(數組 + 連結清單 + 紅黑樹)的存儲結構;

(2)HashMap的預設初始容量為16(1<<4),預設裝載因子為0.75f,容量總是2的n次方;

(3)HashMap擴容時每次容量變為原來的兩倍;

(4)當桶的數量小于64時不會進行樹化,隻會擴容;

(5)當桶的數量大于64且單個桶中元素的數量大于8時,進行樹化;

(6)當單個桶中元素數量小于6時,進行反樹化;

(7)HashMap是非線程安全的容器;

還有一篇回答問題篇,嘿嘿~~

參考:https://blog.csdn.net/tangtong1/article/details/88934809