[Java]深入底層聊HashMap——深入底層的最好開始

本想按照ArrayListLinkedList、HashSet、LinkedHashSet、TreeSet、HashMap、LinkedHashMap、TreeMap的順序介紹容器類的底層的,但是考慮到HashSet其實就是HashMap的一部分(僅僅使用了HashMap的鍵,其值統一使用一個Object對象),所以我們就先行介紹HashMap,這樣我們再介紹HashSet時就簡單的多,而且也更容易大家的理解。

HashMap

我們都知道HashMap底層使用的是一個哈希表來存儲數據,但是什麼是hash表,HashMap是怎麼實現哈希表的我們都尚存疑問。
什麼是哈希表?

	哈希表又稱散列表,是一種通過關鍵值碼直接訪問數據的數據結構。它通過把關鍵碼
值映射到表中的一個位置來訪問記錄,以加快查詢速度。建立這種映射的函數叫做散
列函數,存放記錄的數組稱爲哈希表,關鍵值碼也就是關鍵字的哈希值。

HasMap是怎麼實現哈希表的?

	實現哈希表的關鍵就是建立一個合適散列函數,但是一個找到一個完美的散列函數(
每個關鍵字對應哈希表中一個位置,沒有衝突)幾乎是不可能的,所以在散列函數不
完美的情況下我們要想辦法解決衝突。HashMap中解決衝突的辦法是,每一個哈希表
的位置上都是一個鏈表,這個鏈表中存儲所有關鍵碼值相同的記錄(如下圖所示)。
這樣一來,對於哈希表中的位置我們採用直接訪問的方式,對於鏈表中的記錄(少量
採用順序遍歷的方式訪問。這樣一來就大大加快了對鍵值對的訪問速度。

HashMap的哈希表
哈希表上每一個節點的數據結構如下:

 static class Node<K,V> implements Map.Entry<K,V> {
        /*
         *node的數據域包括hash:key的hash
         *key:關鍵字key
         *value:關鍵字key對應的值value
         *next:指向下一個相同關鍵值碼鏈表中的下一個節點
         */
        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;
        }
		/*
	     *node的相關基本方法
	     */
        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;
        }
		/*
		 *重寫的equals方法
		 */
        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;
        }
    }

put(K key, V value)(添加一個元素)

/**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);  //hash方法用來獲取哈希值
    }

直接調用putVal()方法,對於putVal()方法的具體解釋,請詳細看下面的源碼及註釋(暫時認爲代碼加註釋的解釋方法纔是適合程序員的方法)

/**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key 關鍵字key的hash值
     * @param key the key  關鍵字key
     * @param value the value to put  對應於關鍵字的值
     * @param onlyIfAbsent if true, don't change existing value  如果onlyIfAbsent的值是true,那麼對於已經存在的key將不覆蓋其原來的值
     * @param evict if false, the table is in creation mode.  如果evict的值是false,那麼此表處於創建模式(暫未明白)
     * @return previous value, or null if none  
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
        /*
         *tab:指向本HashMap的哈希表
         *p:
         *n:表示哈希表的長度
         */   
        Node<K,V>[] tab;  Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)  //如果當前hash表尚未初始化或者當前哈希表的長度爲0,則初始化該哈希表(初次put即會初始化哈希表),並初始化n
        //resize方法源碼順次如下
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null) //如果該位置還沒有值。i(關鍵碼值)表示該關鍵字在哈希表中的位置
            tab[i] = newNode(hash, key, value, null);  //將該記錄放到此位置
        else {  
        //hash表中的i位置已經有值了,則用該記錄的關鍵字與鏈表中的記錄比較(使用equals方法)
        //如果該記錄在鏈表中已經存在,則覆蓋其值
        //如果該記錄在鏈表中尚未存在,則在鏈表尾加上一個新的表示該記錄的節點
            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)  //與TreeMap相關暫不做解釋
                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))))  //找到了與該記錄相同的記錄。(哈希值相同,地址相同)和(哈希值相同,equals方法比較相同)都能通過。從這能看出同時重寫hashCode、equals方法的重要性
                        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;
    }

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;   //oldTab指向舊的哈希表
        int oldCap = (oldTab == null) ? 0 : oldTab.length;   //舊的哈希表長度
        int oldThr = threshold;  //threshod的意思是閾值,表示哈希表下一次調整大小的值初始爲0或者默認值16
        int newCap, newThr = 0;
        if (oldCap > 0) {  //如果原來的哈希表已經被初始化並且容量大於0
            if (oldCap >= MAXIMUM_CAPACITY) {  //如果原來的Hash表已經是最大值
                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
            //如果哈希表尚未初始並且threshold不爲0(就是我們使用了HashMap(int initialCapacity, float loadFactor)或者HashMap(int initialCapacity)構造函數時)
            newCap = oldThr;  //容量初始化爲threshod
        else {               // zero initial threshold signifies using defaults
        //如果哈希表尚未初始化(使用了默認構造器),則初始化該哈希表
            newCap = DEFAULT_INITIAL_CAPACITY; //初始化該哈希表長度爲默認值16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);  //閾值初始化爲16 * 0.75
        }
        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;  //返回新表
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章