java.util.HashMap(JDK1.8)

定義

HashMap 是一個(gè)鍵值對(duì)的集合癞松,key值允許為null辟躏,key值不允許重復(fù)。value可重復(fù)涤躲,可null报嵌。

源碼分析

  • 內(nèi)部屬性
    //初始大小
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    //最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //負(fù)載因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //從鏈表變?yōu)榧t黑樹(shù)的鏈表個(gè)數(shù)
    static final int TREEIFY_THRESHOLD = 8;
    //從鏈表變?yōu)榧t黑樹(shù)數(shù)組最小的容量
    static final int MIN_TREEIFY_CAPACITY = 64;
    //hashMap中的實(shí)際存放元素的屬性虱咧,同時(shí)也是個(gè)單向鏈表
    static class Node<K,V> implements Map.Entry<K,V> {
        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;
        }

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

    //Node數(shù)組,存放元素的數(shù)組
    transient Node<K,V>[] table;
    //map的大小
    transient int size;
    //擴(kuò)容的臨界值
    int threshold;
    //負(fù)載因子
    final float loadFactor;
  • 構(gòu)造器
    HashMap 提供了4個(gè)無(wú)參構(gòu)造器沪蓬。其實(shí)值得一看的 只有一個(gè)彤钟。
    如果看重效率,則可以設(shè)置負(fù)載因子低一點(diǎn)跷叉,hash碰撞概率低
    如果看重內(nèi)存逸雹,則可以設(shè)置負(fù)載因子高一點(diǎn)。
    當(dāng)熱云挟,也看情況吧梆砸,想詳細(xì)了解,看下邊的put方法的代碼园欣。
    public HashMap(int initialCapacity, float loadFactor) {
        //判斷初始大小是否合法
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        //判斷負(fù)載因子是否合法
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        //該方法為了讓所有的初始大小都為2的N次方帖世,
        //也就是說(shuō) 當(dāng)你使用Map map = new HashMap(10,0.75f);
        //他的容量并不是10 而是16 沸枯,就是因?yàn)檎{(diào)用了下邊這個(gè)方法日矫。
        //容量為2的N次方可以讓hash值更加分散。減少hash碰撞
        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;
    }
  • 擴(kuò)容
    final Node<K,V>[] resize() {
        //老的table
        Node<K,V>[] oldTab = table;
        //老table容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //老table臨界值
        int oldThr = threshold;
        //新table的容量绑榴,臨界值
        int newCap, newThr = 0;
        //非首次擴(kuò)容 并且 創(chuàng)建HashMap時(shí)沒(méi)有指定大小
        if (oldCap > 0) {
            //如果老的table已經(jīng)擴(kuò)到最大哪轿,則返回原來(lái)的table
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //在判斷中就擴(kuò)容了兩倍,如果新的容量小于最大值并且老的容量大于等于16 則新的臨界值也增加2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //這種情況是翔怎,在構(gòu)造器已經(jīng)指定HashMap的大小
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //首次擴(kuò)容窃诉,使用默認(rèn)的容量和臨界值
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        //如果新的臨界值為0.則設(shè)置
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        //創(chuàng)建擴(kuò)容后的Node數(shù)組
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        //如果oldTal中有數(shù)據(jù),則遷移到newTab中
        if (oldTab != null) {
            //循環(huán)判斷遷移
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //如果該位置上沒(méi)有鏈表赤套,則直接放入
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    //如果該位置放置的是紅黑樹(shù)飘痛,//TODO(分組遷移?)
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    //如果該位置放置的是鏈表
                    //這一步其實(shí)可以這么理解容握,擴(kuò)容后宣脉,數(shù)組下標(biāo)也會(huì)發(fā)生變化。相當(dāng)于是把鏈表分散
                    //下邊 借了個(gè)圖 幫助理解
                    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;
                            //不需要重新計(jì)算hash剔氏,只需要看看原來(lái)的hash值新增的那個(gè)bit是1還是0就好了
                            //是0的話索引沒(méi)變脖旱,是1的話索引變成“原索引+oldCap”
                            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;
    } 
微信圖片_20180205170215.png
  • 添加 put(k,v)
    /**
     * 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);
    }


    /**
     * 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) {
        //tab :table數(shù)組堪遂。p: 鏈表的第一個(gè)位置的元素。n:總?cè)萘棵惹臁:索引位置
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //首次添加,擴(kuò)容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //當(dāng)前索引位置上沒(méi)有元素币旧,直接放入該位置践险。
        //在找位置的時(shí)候 hash & (n-1) 這個(gè)算法也是很厲害的。在1.7的時(shí)候還是hash % n計(jì)算得出索引位置吹菱。
        //該算法效率更高巍虫。 hash & (n-1) = hash % n
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //該位置已經(jīng)有元素了。
            Node<K,V> e; K k;
            //如果該位置的元素hashcode值相等并且通過(guò)equals也相等鳍刷,則直接覆蓋占遥。
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果該元素為紅黑樹(shù),則直接按紅黑樹(shù)處理输瓜。(在鏈表上超過(guò)8個(gè)則為紅黑樹(shù))
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //在該位置的元素下判斷并且以鏈表的方式放入瓦胎。
                for (int binCount = 0; ; ++binCount) {
                    //如果該鏈表下一個(gè)為空,則把這個(gè)鏈下去
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果該鏈表已經(jīng)有8個(gè)了尤揣。則變?yōu)榧t黑樹(shù)搔啊。
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            //在這里,值得一提的是北戏,如果此時(shí)鏈表數(shù)量達(dá)到了8负芋,但是容量沒(méi)有達(dá)到64
                            //則先擴(kuò)容再說(shuō),不變成二叉樹(shù)
                            //關(guān)于紅黑樹(shù)(增加插入嗜愈,查找的效率)旧蛾,等有時(shí)間了(徹底研究明白)在開(kāi)篇文章。
                            treeifyBin(tab, hash);
                        break;
                    }
                    //此時(shí)蠕嫁,如果新添加的和該鏈表上的有相同的 則直接覆蓋锨天,跳出循環(huán),
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //把新的元素變?yōu)橄乱粋€(gè)元素拌阴,繼續(xù)循環(huán)判斷
                    p = e;
                }
            }
            //上邊老說(shuō)覆蓋绍绘,其實(shí)這里是覆蓋的代碼。
            //就是如果重復(fù)了迟赃。則把值賦給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;
    }

 //下邊在借個(gè)圖陪拘,關(guān)于擴(kuò)容的流程.圖來(lái)源(美團(tuán)技術(shù)沙龍)
hashMap put方法執(zhí)行流程圖.png
  • value get(key) 通過(guò)鍵值或者value值。 //如果看懂了put的流程纤壁,那么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;
        //直接跳轉(zhuǎn)到getNode(hash,key)方法
        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;
        //先做一下Node數(shù)組的非空判斷,
        //并且酌媒,通過(guò)hash & (n-1)獲取索引位置賦值給first
        //在這里欠痴,first就是該位置上鏈表的第一個(gè)元素迄靠。
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //如果第一個(gè)元素通過(guò)hash和equals判斷都相等,則直接返回
            //之所以第一步就這么判斷喇辽,是為了效率掌挚。
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //如果該位置是以鏈表存在
            if ((e = first.next) != null) {
                //如果是紅黑樹(shù),則從紅黑樹(shù)中查詢
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                //不是紅黑樹(shù)菩咨,從鏈表中查詢吠式,一直next直到 hash和equals都相等。
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
  • remove(key) 刪除方法
    /**
     * Removes the mapping for the specified key from this map if present.
     *
     * @param  key key whose mapping is to be removed from the map
     * @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 remove(Object key) {
        Node<K,V> e;
        //跳轉(zhuǎn)removeNode方法抽米。
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    /**
     * 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;特占、
        //非空判斷并且賦值 
        //p為該位置的第一個(gè)元素
        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;
            //定義node變量,也就是一會(huì)要?jiǎng)h除的變量
            //接下來(lái)的邏輯是找到node
            //經(jīng)過(guò)判斷 該值就是node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            //如果第一個(gè)不是云茸,就從該鏈表繼續(xù)往下找
            else if ((e = p.next) != null) {
                //如果是紅黑樹(shù)是目,則通過(guò)getTreeNode從紅黑樹(shù)中查詢
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    //不是紅黑樹(shù),一直next找到node
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            //找到node后标捺,因?yàn)閙atchValue為false懊纳。則肯定會(huì)進(jìn)入判斷
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                //如果是紅黑樹(shù),則從紅黑樹(shù)中刪除
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //如果node==p  那么把該位置設(shè)置成node的下一個(gè)宜岛,如果是空长踊,則為空
                else if (node == p)
                    tab[index] = node.next;
                //如果不是,則從新設(shè)置next關(guān)系
                //剛開(kāi)始看著個(gè)的時(shí)候有點(diǎn)懵萍倡。但是后來(lái)發(fā)現(xiàn)了身弊。 
                //如果能進(jìn)到下邊這個(gè)判斷,則p就不是第一個(gè)元素了列敲, 而是node的上一個(gè)元素阱佛,
                //因?yàn)樵谏线呇h(huán)的時(shí)候 有這么一行代碼  p = e;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }
  • 總的來(lái)說(shuō) JDK1.8 無(wú)論是從找索引的位置,還是擴(kuò)容的機(jī)制戴而,還是鏈表變紅黑樹(shù)都增加了效率凑术。
    1.8很不錯(cuò)。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末所意,一起剝皮案震驚了整個(gè)濱河市淮逊,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌扶踊,老刑警劉巖泄鹏,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異秧耗,居然都是意外死亡备籽,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)分井,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)车猬,“玉大人霉猛,你說(shuō)我怎么就攤上這事≈槿颍” “怎么了惜浅?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)伏嗜。 經(jīng)常有香客問(wèn)我赡矢,道長(zhǎng),這世上最難降的妖魔是什么阅仔? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮弧械,結(jié)果婚禮上八酒,老公的妹妹穿的比我還像新娘。我一直安慰自己刃唐,他們只是感情好羞迷,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著画饥,像睡著了一般衔瓮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上抖甘,一...
    開(kāi)封第一講書(shū)人閱讀 51,679評(píng)論 1 305
  • 那天热鞍,我揣著相機(jī)與錄音,去河邊找鬼衔彻。 笑死薇宠,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的艰额。 我是一名探鬼主播澄港,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼柄沮!你這毒婦竟也來(lái)了回梧?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤祖搓,失蹤者是張志新(化名)和其女友劉穎狱意,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體棕硫,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡髓涯,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了哈扮。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片纬纪。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蚓再,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出包各,到底是詐尸還是另有隱情摘仅,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布问畅,位于F島的核電站娃属,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏护姆。R本人自食惡果不足惜矾端,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望卵皂。 院中可真熱鬧秩铆,春花似錦、人聲如沸灯变。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)添祸。三九已至滚粟,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間刃泌,已是汗流浹背凡壤。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蔬咬,地道東北人鲤遥。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像林艘,于是被迫代替她去往敵國(guó)和親盖奈。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容