HashMap 源碼解讀 ?

1、 HashMap 原理= 桶表+鏈表+紅黑樹的結構(jdk1.8)特性

--hashMap 構造函數,有三個構造函數

 1、 無參構造函數,默認初始大小16 和數據加載因子爲0.75

 2、一個參數數的構造函數,可以指定初始值大小,使用默認的數據加載因子0.75

 3、有兩個參數的構造函數,可以指定初始容量和數據加載因子0.75

 /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    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);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

--問題一:爲什麼HashMap的默認值爲16 容量,加載因子爲0.75呢。

      處於一個性能的考慮,因爲每次擴容都是重新創建一個newNode;

      建議: 初始化大小 = 元素個數 / 數據加載因子 +1;

     加載因子:  提高空間利用率和 減少查詢成本的折中,主要是泊松分佈,0.75的話碰撞最小,

--問題二:設置初始化值,比如爲5,那麼Hashmap 是創建容量爲5的容量嗎?

 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);
    }


 /**
     * Returns a power of two size for the given target capacity.
     */
    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;
    }

 從源碼中我們可以看到,設定的初始值最終會調用tableSizeFor 函數;

 這個函數返回一個給定目標2的次方的數。  所以創建的容量cp=8

--問題三: HashMap 是可以存Null 的key值,那麼Null的位置hashmap會放到哪裏呢?

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

   public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

從源碼中可以看出,在進行put 元素操作時,會計算key的hash值,當key爲null 值是放到索引值爲0 的位置的。 

--問題四: put操作時普通的節點是什麼時候轉treeNode節點?

  可以看下put 的源碼

/**
     * 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;
    }

 一行行的分析

if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

  在進行put操作時,首先獲取table對象,判斷對象是否存在,不存在則重置大小。

   table對象是什麼?這個是hashmap內的一個對象。我們發現在構造函數中並沒有初始這個table,顯然這個table值爲null  

 /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

所以在put第一次操作時會調用resize() 方法.reSize()方法作用是

 初始化或加倍表大小。如果爲空,則分配與初始容量目標保持一致。

 if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {

               //to-do
        }

然後繼續往下走,很顯然因爲我們是第一次put 值,所以 tab[i=(n-1)& hash] 的對象是爲null的。所以創建一個對象。

(n-1)&hash 表示查找當前元素的位置,相當於 hash %tab.length 求餘數。

 例如: 當n=8時,hash 值爲4 ,表示tab[4%8]=tab[4] 的位置.

               

然後執行 newNode方法創建一個Node對象,並把key 的hash 值,key值 和value值傳入,第四個參數next 對象,即相關聯的對象。這樣tab[i] 上就賦值成功了。

第二次put插入數據時。執行同樣的操作,同時也會計算hash值,如果hash定位的索引沒有值,則執行相同的操作。

 ++modCount;

這個modCount什麼作用呢?

    1、記錄hashMap 內部結構被修改的次數。

    2、 備用集合迭代器 fail-fast 中?

if (++size > threshold)
            resize();

判斷是否超過了閾值。超過則重新分配表結構。這個this.threshold = tableSizeFor(initialCapacity); 構造函數中設定的。

afterNodeInsertion(evict);
        return null;

/*查找源碼發現是一個空函數*/ 
void afterNodeInsertion(boolean evict) { }

 到這裏put函數執行結束了。考慮下還有這個情況。

  1、 當key 的hash值相當的時候,就會走這段代碼了。

 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;
            }
 Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

 p對象是一個對象,在判斷的時候已經賦值了,如if ((p = tab[i = (n - 1) & hash]) == null)

上面這段代碼的意思是 判斷hash值是否相同,相同的化,判斷key 是否相等,如果相等就e=p這一步。主要作用用於修改存在key值的value值。

 if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }

/**這個是空函數*/
void afterNodeAccess(Node<K,V> p) { }

 這段代碼用於修改value。並返回舊值。這裏就結束了,不在往下走了。

在看另外的情況:這裏修改舊值的另一次情況。

 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;
                }
            }

我先來看else 中代碼,這個是一個無限循環語句,如果裏面無法跳出。就一直進行循環。

這段代碼的意思是 key 的hash 值 和某上一次的key的hash值相同,所以會在查到到當前的p對象.next賦值,形成鏈表,這裏稱爲 hash碰撞。會把存的值形成鏈表結構。

創建一個節點對象存入p.next中,指的是第一次hash碰撞,進入

 if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }

 這裏有一個判斷binCount 顯然第一次是小於TREEIFY_THRESHOLD - 1的值的,TREEIFY_THRESHOLD=8 默認值。

假設這裏是put插入值的第7次hash碰撞,每次選好 p = e; 對象賦值。

這個時候代碼執行  treeifyBin(tab, hash);

這個方法做了什麼呢?

 final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        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在 tab.length長度小於MIN_TREEIFY_CAPACITY=64的時候,在轉化成鏈表結構。主要出於性能和空間使用率的考慮。

這裏爲了簡便我們直接看else if 的代碼 ?

TreeNode<K,V> p = replacementTreeNode(e, null);

這一步是轉化操作,把Node對象轉成一個TreeNode對象。

 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);

這個步驟主要是替換tab 中index=hash 這一隻的對象Node 爲TreeNode,如果這個TREEIFY_THRESHOLD 這個值比較大時,Node的鏈表就比較長,在插入或者查詢時會影響性能。

TREEIFY_THRESHOLD=8 爲什麼呢?

這個值也必須是2 的倍數,以符合最小應爲8*關於轉換回普通垃圾箱的樹刪除.

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;
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }

把普通node 對象轉成treenode樹。

爲什麼TreeNode 可以轉化成Node對象 ?

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);
        }
    }

  static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {

從代碼中可以看出TreeNode 繼承了Node對象,是Node對象的子類。顧可以相互轉化。

上面的紅黑樹的查詢0Logn

-----講完了put方法,現在來說下get方式

 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;
        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;
    }

  get方法裏面調用的是getNode方式。

 在getNode方法中進行獲取查詢,在其中判斷了請求的節點對象是否爲treeNode,如果TreeNode通過getTreeNode進行獲取值。

如果不是就是進行一個循環查找到has對應的位置,判斷key,返回查找的對象,發現時間複雜度爲O(n).

getTreeNode

  --> find 方法 進行對象的查找。

 public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

fail-fast 機制?

fail-fast 機制,即快速失敗機制,是java集合(Collection)中的一種錯誤檢測機制。當在迭代集合的過程中該集合在結構上發生改變的時候,就有可能會發生fail-fast,即拋出ConcurrentModificationException異常。fail-fast機制並不保證在不同步的修改下一定會拋出異常,它只是盡最大努力去拋出,所以這種機制一般僅用於檢測bug。


 

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