1. 程式人生 > >HashMap主要方法原始碼分析(JDK1.8)

HashMap主要方法原始碼分析(JDK1.8)

本篇從HashMap的put、get、remove方法入手,分析原始碼流程 (不涉及紅黑樹的具體演算法) jkd1.8中HashMap的結構為陣列、連結串列、紅黑樹的形式     (未轉化紅黑樹時)  

 (轉化為紅黑樹時的情況)


 

一、關於HashMap需要了解的靜態常量

DEFAULT_INITIAL_CAPACITY 陣列預設初始容量 16 DEFAULT_LOAD_FACTOR 預設負載因子 0.75 MIN_TREEIFY_CAPACITY 最小樹容量 64 在下面的方法探究中將會提到這些靜態常量的用處   

二、方法探究

1、put

HashMap中的陣列是第一次呼叫put方法時才建立物件的

下面是從進入put到建立完陣列的全過程

 

 將key、value作為引數傳入後,計算key的hash,再傳入putVal方法

/**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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;
    }

putVal()的整個流程如下         1、先判斷table是否為null,如果是,呼叫resize()  
/**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    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) {
            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;
    }
resize resize(): 判斷當前table為null後,初始化負載因子DEFAULT_LOAD_FACTOR 計算當前陣列邊界DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY (第一次陣列邊界為16*0.75=12,當陣列超過陣列邊界時會擴大為兩倍。 也就是說陣列中的元素達到或大於12時,將第一次擴大陣列,大小變為16*2=32) 建立並返回大小為DEFAULT_INITIAL_CAPACITY的table物件。 (總的來說resize負責擴大陣列容量和初始化陣列)

 

以上就是呼叫put方法時HashMap物件內陣列的建立過程
2、如果進入putVal()判斷table不為null 利用hash值與(&)計算出陣列下標,並判斷是否為空 如果是,建立node物件並存入陣列 如果不是,從當前下標的連結串列第一位開始一個個往下對比 ①若hash和key值都相同,則break退出迴圈,之後進行value的替換,並返回oldValue ②若過程中遇到null,則建立node物件   判斷是否達到紅黑樹轉換條件:如果當前連結串列長度達到8,進入treeifyBin方法   判斷表長度(如果小於64,則呼叫resize(),判斷要不要增大陣列   反之replacementTreeNode,用紅黑樹代替當前連結串列

(向下遍歷陣列當前下標連結串列的操作)

(key相同時value的替換操作)


 

3、增加size(map中元素的數量)和modCount(對map的操作次數)

 

2、get

* Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
get 將key和key的hash傳入getNode方法,並獲取返回的Node物件的value 先判斷陣列不為null,且長度大於0 利用hash值先找到node可能在的列的第一個元素(當前傳入key可能不存在) 再豎向遍歷連結串列對比hash和key值

(上面的first即為node可能存在的連結串列的第一個元素) 

查詢時如果第一個即匹配則直接返回

 否則往下遍歷直到匹配或node為null

 

3、removeNode

/**
     * Implements Map.remove and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
    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;
        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;
    }
removeNode

與getNode的邏輯類似,利用hash值查詢可能存在的位置

如果連結串列第一位就匹配:

對連結串列的遍歷:

判斷node的型別,如果是連結串列則用node.nest來代替當前位置

最後運算元+1,size-1,返回被remove的node物件

            &nbs