Java,java官網

來源:互聯網
上載者:User

Java,java官網

興趣所致研究一下HashMap的源碼,寫下自己的理解,基於JDK1.8。

本文大概分析HashMap的put(),get(),resize()三個方法。

 

首先讓我們來看看put()方法。

    public V put(K key, V value) {        return putVal(hash(key), key, value, false, true);    }
    /**     * 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;    }

 

1.首先通過hash(key)計算key的hash值

putVal(hash(key), key, value, false, true)

2.由於hashMap實際儲存資料的就是table數組,那麼首先需要判斷table數組是否已經被初始化了,如果沒有初始化,那麼調用resize()方法對table進行初始化

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

3.通過hash與(n-1)進行與運算得出數組的索引,根table[索引]判斷是否為null,如果為null那麼直接存入該位置。

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

4.如果table[索引]不為null,那麼說明位置發生了碰撞,需要繼續進行判斷

5.如果判斷table[索引]位置p上的p.key=key&&p.hash=hash,那麼就會對value進行替換,也就是保證key唯一。

6.如果不滿足5的條件,那麼會判斷table[索引]位置p是二叉樹,那麼會調用TreeNode.putTreeVal()去進行對二叉樹節點的插入。

else if (p instanceof TreeNode)                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

7.如果不滿足5,6的條件,那麼會使用鏈表來插入該節點:迴圈尋找p.next直到找到一個位置為null那麼進行插入。

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

8.上述5,6,7三步中,只要發現了p.key=key&&p.hash=hash,那麼就會進行value替換,將oldValue替換為newValue。

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

9.進行計數+1,並且判斷當前已存數量是否大於table[]的2/3,如果大於那麼使用resize()對table進行擴充。

10.至此整個put()完成。

 

再來讓我們看看get()方法。

    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     *     * @param hash hash for key     * @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) {            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.首先判斷table[]是否為空白,通過hash計算索引判斷table[索引]是否為空白,如果任意一項為空白那麼直接return null。

2.判斷table[索引]的hash與key是否都與尋找的相同,如果hash與key都相同,那麼直接返回table[索引]。

if (first.hash == hash && // always check first node                ((k = first.key) == key || (key != null && key.equals(k))))                return first;

3.如果不滿足條件2,那麼判斷table[索引]的next是否為空白,如果為空白則return null。

4.如果table[索引]的next不為空白,那麼判斷是否為二叉樹,如果是二叉樹直接使用getTreeNode()方法尋找。

if (first instanceof TreeNode)                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);

5.如果不是二叉樹,那麼直接使用鏈表的方式尋找。

        do {                    if (e.hash == hash &&                        ((k = e.key) == key || (key != null && key.equals(k))))                        return e;                } while ((e = e.next) != null);

6.至此完成整個get()方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.