Java集合 HashMap解析(源碼分析)

目錄:

一、數據結構
二、常用構造
三、常用屬性
四、常用方法put()
五、常用方法get()
六、常用方法remove()

一、數據結構

1.hashmap的數據結構由數組+鏈表(鏈表太長的話就轉化爲紅黑樹)
2.繼承map的鍵值對
3.hashMap數據結構圖解;
在這裏插入圖片描述

二、常用構造

1. 4個常用構造的瞭解

在這裏插入圖片描述

2. 我們重點了解1 無參構造(看源碼)

【初始化容量 16,負載因子 0.75】
在這裏插入圖片描述

三、常用屬性

只有一些常量,無常用屬性

四、常用方法put()

1.put()方法

在這裏插入圖片描述

2.put()方法調用的hash(key)方法

在這裏插入圖片描述

3. (重點)put()方法調用的putVal()方法。

源碼:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //【1,如果table 沒有初始化,就resize()初始化.】
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    //【2.通過hash值找到元素的位置,如果元素value爲空,將數據存放進去。創建新的node。】
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    //【3.如果hash值對應的value有值?】
    else {
        Node<K,V> e; K k;
        //【3.1 如果hash值相等,並且key值相等。就替換】
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        //【3.2如果key值不相等,且掛在hash值數組上的,key的數據結構爲 TreeNode。使用紅黑樹插入。】
        //【新增知識點:紅黑樹插入putTheeVal()】
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        //【3.3 如果key不等,且有不用紅黑樹,就是用鏈表插入。】
        else {
            //3.3.1循環哈希值hash  p  下的所有鏈表。
            for (int binCount = 0; ; ++binCount) {
                //3.3.2.1 如果下一個鏈表爲空,就新增加新的鏈表。
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    //3.3.2.2 如果鏈表的的長度過長,就把鏈表轉化爲紅黑樹。
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                //3.3.3 ,判斷插入成功,跳出循環。
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        //【3.4經過上面的循環,如果e不爲空,就證明插入成功,更新指定位置的鍵值對。】
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    //【4.添加後再次判斷大小,過大就resize()擴容】
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

總結:
1.如果table沒有初始化,就會對table進行resize()初始化
2.如果 初始化 且 hash值未知的的爲空,就直接將存放。
3.如果初始化 且不爲空就執行以下操作,插入
(1)3.1 如果hash值相等,並且key值相等。就替換
(2)3.2如果key值不相等,且掛在hash值數組上的,key的數據結構爲 TreeNode。使用紅黑樹插入
(3)else 不爲紅黑樹,爲鏈表執行以下操作

  • 1.遍歷鏈表
  • 2.下一個爲空,就插入數據,(1)2.插入後判斷鏈表長度,如果過長,就轉換爲紅黑樹。
  • 3.如果插入成功,就break。問題:鏈表上的所有key沒有判斷是否和插入的key相等啊?

(4)紅黑樹或者鏈表插入完成後,更新鍵值對
4.插入完成後就再次判斷大小,如果過大就擴容。

4. 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.
 * 【初始化默認容量,或者增加容量在2次冪偏移,容量大小*2 】
 *
 * @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;
    //【1.舊容量oldCap > 0 (已經初始化)】
    if (oldCap > 0) {
        //【1.1 舊容量 >= 最大值,就不再擴容,把閾值設置爲最大值】
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //【1.2.如果容量還可以擴容,就擴大 2倍。】
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    //【2.舊容量>0不成立,但舊閾值(threshold門檻) > 0,把舊門檻的值賦值給新的 容量】
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    //【3.如果1,2都不成立,容量和門檻都爲0,初始化閾值和門檻爲默認值】
    //這裏解決了 無參構造方法,不對閾值和容量進行初始化的問題。
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //閾值爲0??
    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"})
    //【4.更新數據桶(哈希值的數組鏈條,用來保存不同的哈希值,下面掛着鏈條或者紅黑樹,】
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    //【5.把舊的數據移動到新數據桶裏面】
    //如果之前的數組桶裏面已經存在數據,由於table容量發生變化,hash值也會發生變化,需要重新計算下標
    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;
}

總結:
1.判斷是否初始化,沒有初始化就初始化容器和閾值
(1)如果初始化了 且 擴容後不超過 閾值,【擴容 2倍】
(2)超過閾值,就讓閾值等於新的容量
2.擴容後創建新的table數據桶,把舊的數據移動到新的數據桶裏
(1)如果hash值的位置爲空,就直接插入值
(2)如果hash值位置爲鏈表,就重新計算下標,分組鏈表
(3)如果是紅黑樹,就拆分操作。
注意:這個地方有些東西看不懂,等下回頭再研究,現在瞭解他的具體使用就可以了。

五、常用方法 get()

1。get()方法

在這裏插入圖片描述

3. getNode()方法

    /**
     * Implements Map.get and related methods.【實現get()的方法 getNode()】
     *
     * @param hash hash for key【獲取key的hash】
     * @param key the key
     * @return the node, or null if none
     */
    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) {
            //【1.如果第一個值就是 查找的 key,直接誒取出】
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                //【2.如果第一個值不是,且是樹結構TreeNode,就是用樹查找】
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                //【3.鏈表,就是用遍歷鏈表的查找】
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

總結:
1.第一個key匹配,直接誒取出
2.第一個key不匹配,且是樹結構 TreeNode,就是用樹查找
3.第一個key不匹配,且是鏈表結構,就是用遍歷鏈表查找

樹查找等待補充

六、remove()方法

1.remove()

在這裏插入圖片描述

2. removeNode()方法

 /**
  * Implements Map.remove and related(相關的) methods.
  * 【實現 Map.remove() 的相關的方法】
  *
  * @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;
     //【1.更具hash值查找對對應的數組的位置】
     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);
             }
         }
         //【2.如果找到,就進行移除】
         if (node != null && (!matchValue || (v = node.value) == value ||
                              (value != null && value.equals(v)))) {
             //【2.1 如果是該 hash值的位置是 掛了一顆 紅黑樹,就進行“樹移除”】
             if (node instanceof TreeNode)
                 ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
             //【2.2 如果掛了 鏈表,就把索引指向下一個鏈表就可以了】
             else if (node == p)
                 tab[index] = node.next;
             else
                 p.next = node.next;
             ++modCount;
             --size;
             afterNodeRemoval(node);
             return node;
         }
     }
     return null;
 }

總結:和get()方法幾乎一致。

七、遇到的其他方法解析

1.hash()方法,

1.代碼

 static final int hash(Object key) {
    int h;
    //【hash()返回hashCode的計算後的值】
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

2,總結:
這個代碼叫做擾動函數,也就是 hashCode()中的 的hash運算,如下
(1)獲取key的hash值(hashCode()),根據地址獲得的int值
(2)hashCode右移動 16位,並且和 原來的 hashCode進行 ^(異或運算 不同爲真 1??),(讓高低位進行混合,讓兩者都參與運算,讓hash值更加均勻)

2. 取模運算 (n-1)& hash

HashMap 的很多源碼中可以看到類似的表達。

first = tab[(n - 1) & hash]) 

hash算法中,爲了高速度地讓元素分佈更加均勻,使用特殊取模運算。因爲&的效率要遠遠大於 %,並且只有在 n 爲 2的次冪的時候 纔能有取模的效果。
由HashMap哈希算法引出的求餘%和與運算&轉換問題

參考博客:
https://juejin.im/post/5c8f461c5188252da90125ba#heading-2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章