JAVA讀源碼之-HashMap

JAVA讀源碼之-HashMap

提交于 2021-01-11
本篇文章是類似筆記的形式。文筆寫不好出嘹,而且會(huì)大量摘抄別人的文章只祠。

底層結(jié)構(gòu)

數(shù)組+ 鏈表+ 紅黑樹

image

類圖

image
image

內(nèi)部結(jié)構(gòu)

Node<k,V>

HashMap中元素是通過 Node數(shù)組爷绘、Node鏈表垂蜗、紅黑樹存儲(chǔ)的。 Node起到承載數(shù)據(jù)的作用解幽,也是通過Node實(shí)現(xiàn)鏈表的贴见。


 /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        //可以理解為Hash地址。不過是經(jīng)過擾動(dòng)的Hash地址
        final int hash;
        // 也就是Map的key
        final K key;
        // 也就是Map的value 
        V value;
        // 鏈表結(jié)構(gòu)躲株。hash碰撞出現(xiàn)的話片部。會(huì)存到next中。 可以看上面的示意圖霜定。
        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;
        }

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

類定義

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {}

AbstractMap :   抽抽象類档悠。提供方法封裝廊鸥。 不過HashMap把大部分方法重寫了。就不一一列舉了辖所。
Cloneable   :   克隆惰说。
     - cloneable其實(shí)就是一個(gè)標(biāo)記接口,只有實(shí)現(xiàn)這個(gè)接口后缘回,然后在類中重寫Object中的clone方法吆视,然后通過類調(diào)用clone方法才能克隆成功,如果不實(shí)現(xiàn)這個(gè)接口酥宴,則會(huì)拋出CloneNotSupportedException(克隆不被支持)異常啦吧。
     - 相關(guān)聯(lián)的知識(shí)還有深克隆和淺克隆
     - 設(shè)計(jì)模式 `原型模式` 就是依據(jù) cloneable 接口實(shí)現(xiàn)的。感興趣的可以看一下幅虑。
Serializable:   序列化

代碼分析

常量


 /**
     * The default initial capacity - MUST be a power of two.
     *
     * 缺省table大小
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     *
     * table最大長度
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     *
     * 缺省負(fù)載因子大小
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     *
     * 樹化閾值
     * 插入數(shù)據(jù)時(shí)丰滑,如果鏈表過長時(shí),將鏈表轉(zhuǎn)化為紅黑樹
     * 具體算法看代碼
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     *
     * 樹降級(jí)稱為鏈表的閾值
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     *
     * 樹化的另一個(gè)參數(shù)倒庵,當(dāng)哈希表中的所有元素個(gè)數(shù)超過64時(shí)褒墨,才會(huì)允許樹化
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

重點(diǎn)

  • 數(shù)化

Todo

成員變量

transient java關(guān)鍵字。表示不序列化 百度百科


 /* ---------------- Fields -------------- */

    /**
     * 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.)
     *
     * 哈希表
     *
     * 什么時(shí)候初始化擎宝?
     * //延遲初始化邏輯郁妈,第一次調(diào)用putVal時(shí)會(huì)初始化hashMap對象中的最耗費(fèi)內(nèi)存的散列表
     *  if ((tab = table) == null || (n = tab.length) == 0)
     *       n = (tab = resize()).length;
     *
     */
    transient Node<K,V>[] table;

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * The number of key-value mappings contained in this map.
     * 當(dāng)前哈希表中元素個(gè)數(shù)
     */
    transient int size;

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     *
     * 當(dāng)前哈希表結(jié)構(gòu)修改次數(shù)
     */
    transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * 擴(kuò)容閾值,當(dāng)你的哈希表中的元素超過閾值時(shí)绍申,觸發(fā)擴(kuò)容
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;

    /**
     * The load factor for the hash table.
     *
     * 負(fù)載因子
     *
     * threshold = capacity * loadFactor
     *
     * @serial
     */
    final float loadFactor;

構(gòu)造方法

 /* ---------------- Public operations -------------- */

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity 初始容量
     * @param  loadFactor      the load factor 負(fù)載因子
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int initialCapacity, float loadFactor) {

        //其實(shí)就是做了一些校驗(yàn)
        //capacity必須是大于0 噩咪,最大值也就是 MAX_CAP
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                    initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;

        //loadFactor必須大于0
        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
    }

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

    /**
     * Implements Map.putAll and Map constructor.
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                        (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }


tableSizeFor

位運(yùn)算(二進(jìn)制,說實(shí)話看不懂)

   /**
     * Returns a power of two size for the given target capacity.
     * 作用:返回一個(gè)大于等于當(dāng)前值cap的一個(gè)數(shù)字极阅,并且這個(gè)數(shù)字一定是2的次方數(shù)
     *
     * cap = 10
     * n = 10 - 1 => 9
     * 0b1001 | 0b0100 => 0b1101
     * 0b1101 | 0b0011 => 0b1111
     * 0b1111 | 0b0000 => 0b1111
     *
     * 0b1111 => 15
     *
     * return 15 + 1;
     *
     * cap = 16
     * n = 16;
     * 0b10000 | 0b01000 =>0b11000
     * 0b11000 | 0b00110 =>0b11110
     * 0b11110 | 0b00001 =>0b11111
     * =>0b11111 => 31
     * return 31 + 1;
     *
     * 0001 1101 1100 => 0001 1111 1111 + 1 => 0010 0000 0000 一定是2的次方數(shù)
     *
     */
    static final int tableSizeFor(int cap) {
        int n = cap;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        
        // 套娃三目運(yùn)算
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

put方法

image
/**
     * 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>.)
     *   返回先前key對應(yīng)的value值(如果value為null胃碾,也返回null),如果先前不存在這個(gè)key筋搏,那么返回的就是null仆百;
     */
    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:表示當(dāng)前hashMap的散列表
        //p:表示當(dāng)前散列表的元素
        //n:表示散列表數(shù)組的長度
        //i:表示路由尋址 結(jié)果
        Node<K,V>[] tab; Node<K,V> p; int n, i;

        //延遲初始化邏輯,第一次調(diào)用putVal時(shí)會(huì)初始化hashMap對象中的最耗費(fèi)內(nèi)存的散列表
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

        //最簡單的一種情況:尋址找到的桶位 剛好是 null奔脐,這個(gè)時(shí)候俄周,直接將當(dāng)前k-v=>node 扔進(jìn)去就可以了
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

        else {
            //e:不為null的話,找到了一個(gè)與當(dāng)前要插入的key-value一致的key的元素
            //k:表示臨時(shí)的一個(gè)key
            Node<K,V> e; K k;

            //表示桶位中的該元素髓迎,與你當(dāng)前插入的元素的key完全一致峦朗,表示后續(xù)需要進(jìn)行替換操作
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

            else if (p instanceof TreeNode)//紅黑樹,下期講排龄。進(jìn)QQ群:865-373-238
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //鏈表的情況波势,而且鏈表的頭元素與我們要插入的key不一致。
                for (int binCount = 0; ; ++binCount) {
                    //條件成立的話,說明迭代到最后一個(gè)元素了艰亮,也沒找到一個(gè)與你要插入的key一致的node
                    //說明需要加入到當(dāng)前鏈表的末尾
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //條件成立的話闭翩,說明當(dāng)前鏈表的長度,達(dá)到樹化標(biāo)準(zhǔn)了迄埃,需要進(jìn)行樹化
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            //樹化操作
                            treeifyBin(tab, hash);
                        break;
                    }
                    //條件成立的話疗韵,說明找到了相同key的node元素,需要進(jìn)行替換操作
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }

            //e不等于null侄非,條件成立說明蕉汪,找到了一個(gè)與你插入元素key完全一致的數(shù)據(jù),需要進(jìn)行替換
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }

        //modCount:表示散列表結(jié)構(gòu)被修改的次數(shù)逞怨,替換Node元素的value不計(jì)數(shù)
        ++modCount;
        //插入新元素者疤,size自增,如果自增后的值大于擴(kuò)容閾值叠赦,則觸發(fā)擴(kuò)容驹马。
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }


hash 方法

  • 小知識(shí)。 key是null的話除秀。那它一定是放在第0位糯累。 (key == null) ? 0 :
  • 這就是前面有說的擾動(dòng)方法,讓key值算出的hash值更均勻册踩,減少hash碰撞的幾率泳姐。也就提高了性能。 hash碰撞多了,就會(huì)加快數(shù)據(jù)向鏈表轉(zhuǎn)化暂吉,向樹轉(zhuǎn)化拉宗。

    /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     *
     * 作用:讓key的hash值的高16位也參與路由運(yùn)算
     * 異或:相同則返回0镀脂,不同返回1
     *
     * h = 0b 0010 0101 1010 1100 0011 1111 0010 1110
     * 0b 0010 0101 1010 1100 0011 1111 0010 1110
     * ^
     * 0b 0000 0000 0000 0000 0010 0101 1010 1100
     * => 0010 0101 1010 1100 0001 1010 1000 0010
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

resize方法

重新計(jì)算大小。會(huì)涉及到鏈表轉(zhuǎn)換和樹化躲查。也就是咱們說的自動(dòng)擴(kuò)容

  //插入新元素肾扰,size自增阿逃,如果自增后的值大于擴(kuò)容閾值林束,則觸發(fā)擴(kuò)容横漏。
  if (++size > threshold)
     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.
     *
     * 為什么需要擴(kuò)容?
     * 為了解決哈希沖突導(dǎo)致的鏈化影響查詢效率的問題低散,擴(kuò)容會(huì)緩解該問題。
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
        //oldTab:引用擴(kuò)容前的哈希表
        Node<K,V>[] oldTab = table;
        //oldCap:表示擴(kuò)容之前table數(shù)組的長度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //oldThr:表示擴(kuò)容之前的擴(kuò)容閾值骡楼,觸發(fā)本次擴(kuò)容的閾值
        int oldThr = threshold;
        //newCap:擴(kuò)容之后table數(shù)組的大小
        //newThr:擴(kuò)容之后熔号,下次再次觸發(fā)擴(kuò)容的條件
        int newCap, newThr = 0;

        //條件如果成立說明 hashMap中的散列表已經(jīng)初始化過了,這是一次正常擴(kuò)容
        if (oldCap > 0) {
            //擴(kuò)容之前的table數(shù)組大小已經(jīng)達(dá)到 最大閾值后鸟整,則不擴(kuò)容引镊,且設(shè)置擴(kuò)容條件為 int 最大值。
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }

            //oldCap左移一位實(shí)現(xiàn)數(shù)值翻倍,并且賦值給newCap弟头, newCap 小于數(shù)組最大值限制 且 擴(kuò)容之前的閾值 >= 16
            //這種情況下吩抓,則 下一次擴(kuò)容的閾值 等于當(dāng)前閾值翻倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }

        //oldCap == 0,說明hashMap中的散列表是null
        //1.new HashMap(initCap, loadFactor);
        //2.new HashMap(initCap);
        //3.new HashMap(map); 并且這個(gè)map有數(shù)據(jù)
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;

        //oldCap == 0,oldThr == 0
        //new HashMap();
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;//16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//12
        }

        //newThr為零時(shí)赴恨,通過newCap和loadFactor計(jì)算出一個(gè)newThr
        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)建出一個(gè)更長 更大的數(shù)組
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;

        //說明疹娶,hashMap本次擴(kuò)容之前,table不為null
        if (oldTab != null) {

            for (int j = 0; j < oldCap; ++j) {
                //當(dāng)前node節(jié)點(diǎn)
                Node<K,V> e;
                //說明當(dāng)前桶位中有數(shù)據(jù)伦连,但是數(shù)據(jù)具體是 單個(gè)數(shù)據(jù)雨饺,還是鏈表 還是 紅黑樹 并不知道
                if ((e = oldTab[j]) != null) {
                    //方便JVM GC時(shí)回收內(nèi)存
                    oldTab[j] = null;

                    //第一種情況:當(dāng)前桶位只有一個(gè)元素,從未發(fā)生過碰撞惑淳,這情況 直接計(jì)算出當(dāng)前元素應(yīng)存放在 新數(shù)組中的位置额港,然后
                    //扔進(jìn)去就可以了
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;

                    //第二種情況:當(dāng)前節(jié)點(diǎn)已經(jīng)樹化,本期先不講歧焦,下一期講移斩,紅黑樹。QQ群:865-373-238
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        //第三種情況:桶位已經(jīng)形成鏈表

                        //低位鏈表:存放在擴(kuò)容之后的數(shù)組的下標(biāo)位置绢馍,與當(dāng)前數(shù)組的下標(biāo)位置一致向瓷。
                        Node<K,V> loHead = null, loTail = null;
                        //高位鏈表:存放在擴(kuò)容之后的數(shù)組的下表位置為 當(dāng)前數(shù)組下標(biāo)位置 + 擴(kuò)容之前數(shù)組的長度
                        Node<K,V> hiHead = null, hiTail = null;

                        Node<K,V> next;
                        do {
                            next = e.next;
                            //hash-> .... 1 1111
                            //hash-> .... 0 1111
                            // 0b 10000

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

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;
        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) {
        //tab:引用當(dāng)前hashMap的散列表
        //first:桶位中的頭元素
        //e:臨時(shí)node元素
        //n:table數(shù)組長度
        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) {
            //第一種情況:定位出來的桶位元素 即為咱們要get的數(shù)據(jù)
            if (first.hash == hash && // always check first node
                    ((k = first.key) == key || (key != null && key.equals(k))))
                return first;

            //說明當(dāng)前桶位不止一個(gè)元素,可能 是鏈表 也可能是 紅黑樹
            if ((e = first.next) != null) {
                //第二種情況:桶位升級(jí)成了 紅黑樹
                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;
    }

remove方法



    /**
     * 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;
        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) {
        //tab:引用當(dāng)前hashMap中的散列表
        //p:當(dāng)前node元素
        //n:表示散列表數(shù)組長度
        //index:表示尋址結(jié)果
        Node<K,V>[] tab; Node<K,V> p; int n, index;

        if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {
            //說明路由的桶位是有數(shù)據(jù)的痕貌,需要進(jìn)行查找操作风罩,并且刪除

            //node:查找到的結(jié)果
            //e:當(dāng)前Node的下一個(gè)元素
            Node<K,V> node = null, e; K k; V v;

            //第一種情況:當(dāng)前桶位中的元素 即為 你要?jiǎng)h除的元素
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;


            else if ((e = p.next) != null) {
                //說明,當(dāng)前桶位 要么是 鏈表 要么 是紅黑樹

                if (p instanceof TreeNode)//判斷當(dāng)前桶位是否升級(jí)為 紅黑樹了
                    //第二種情況
                    //紅黑樹查找操作舵稠,下一期再說
                    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);
                }
            }


            //判斷node不為空的話超升,說明按照key查找到需要?jiǎng)h除的數(shù)據(jù)了
            if (node != null && (!matchValue || (v = node.value) == value ||
                    (value != null && value.equals(v)))) {

                //第一種情況:node是樹節(jié)點(diǎn),說明需要進(jìn)行樹節(jié)點(diǎn)移除操作
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);

                //第二種情況:桶位元素即為查找結(jié)果哺徊,則將該元素的下一個(gè)元素放至桶位中
                else if (node == p)
                    tab[index] = node.next;

                else
                    //第三種情況:將當(dāng)前元素p的下一個(gè)元素 設(shè)置成 要?jiǎng)h除元素的 下一個(gè)元素室琢。
                    p.next = node.next;

                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }


replace方法



    @Override
    public boolean replace(K key, V oldValue, V newValue) {
        Node<K,V> e; V v;
        if ((e = getNode(hash(key), key)) != null &&
                ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            afterNodeAccess(e);
            return true;
        }
        return false;
    }

    @Override
    public V replace(K key, V value) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }

中文注釋后的源碼

鏈接 》

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市落追,隨后出現(xiàn)的幾起案子盈滴,更是在濱河造成了極大的恐慌,老刑警劉巖轿钠,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件巢钓,死亡現(xiàn)場離奇詭異,居然都是意外死亡疗垛,警方通過查閱死者的電腦和手機(jī)症汹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來贷腕,“玉大人背镇,你說我怎么就攤上這事咬展。” “怎么了瞒斩?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵破婆,是天一觀的道長。 經(jīng)常有香客問我胸囱,道長祷舀,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任旺矾,我火速辦了婚禮蔑鹦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘箕宙。我一直安慰自己嚎朽,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布柬帕。 她就那樣靜靜地躺著哟忍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪陷寝。 梳的紋絲不亂的頭發(fā)上锅很,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機(jī)與錄音凤跑,去河邊找鬼爆安。 笑死,一個(gè)胖子當(dāng)著我的面吹牛仔引,可吹牛的內(nèi)容都是我干的扔仓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼咖耘,長吁一口氣:“原來是場噩夢啊……” “哼翘簇!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起儿倒,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤版保,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后夫否,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體彻犁,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年凰慈,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了汞幢。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,919評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡溉瓶,死狀恐怖急鳄,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情堰酿,我是刑警寧澤疾宏,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站触创,受9級(jí)特大地震影響坎藐,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜哼绑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一岩馍、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧抖韩,春花似錦蛀恩、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至席揽,卻和暖如春顽馋,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背幌羞。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工寸谜, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人属桦。 一個(gè)月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓熊痴,卻偏偏與公主長得像,于是被迫代替她去往敵國和親地啰。 傳聞我的和親對象是個(gè)殘疾皇子愁拭,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評論 2 354

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