HashMap源碼解析(一)

HashMap<K,V>類介紹

HashMap是散列結構,這種結構是支持快速查找的。經過Key計算哈希碼,經過哈希碼定位到具體的Value(固然具體過程不會這麼簡單)。在JDK8中HashMap進行了改進,引入了紅黑樹。JDK8中HashMap是數組+鏈表+紅黑樹的複合數據結構。 注意:這一篇文章咱們先分析HashMap中和紅黑樹操做無關的部分。java

HashMap結構

HashMap中相關字段

/**
 * The default initial capacity - MUST be a power of two.
 */
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.
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * The load factor used when none specified in constructor.
 */
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.
 */
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.
 */
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.
 */
static final int MIN_TREEIFY_CAPACITY = 64;

/* ---------------- 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.)
 */
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.
 */
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).
 */
transient int modCount;

/**
 * The next size value at which to resize (capacity * load factor).
 *
 * @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.
 *
 * @serial
 */
final float loadFactor;
複製代碼

從上面註釋咱們知道:node

  • DEFAULT_INITIAL_CAPACITY這個字段表示默認table數組的長度,默認是16。
  • TREEIFY_THRESHOLD表示桶中鏈表長度達到8個時,會嘗試轉化爲紅黑樹,後面會介紹。
  • threshold計算出來的閾值,若是HashMap中存儲的元素超過這個閾值,會經過resize進行擴容。
  • loadFactor加載因子,默認是0.75,咱們能夠在構造函數中進行動態調整。

HashMap中鏈表節點Node結構

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

    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;
    }
}
複製代碼

從源碼中咱們看到Node節點的結構仍是很清晰的,hash,Key,Value和next連接。因此在HashMap中鏈表只是單鏈表,LinkedList中的Node是雙向鏈表。算法

HashMap相關構造函數

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

/**
 * 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);
}
複製代碼
  • HashMap默認都會設置加載因子,咱們能夠設置加載因子。若是大於0.75,那麼Map的利用率是提高(閾值變大,擴容延後了)。這樣可能會致使Map發生碰撞的概率更高(查找元素會相對慢一些)。若是小於0.75,那麼擴容相對頻繁寫,可是查找元素可能會快一點(Map發生碰撞的概率小了)。0.75是一個平衡,通常無需作修改。
  • initialCapacity做爲參數傳遞進來時,會經過tableSizeFor方法計算大於等於輸入參數的的最小的2的指數冪 例如參數是15,那麼輸出16;參數是22,輸出32。保證HashMap數組長度是2的冪次方。
  • 若是參數是Map的話,直接調用putMapEntries插入元素。下面咱們來分析這個函數。

putMapEntries分析

/**
 * 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);
        }
    }
}
複製代碼
  • 先根據map的大小來計算須要多大的散列表。若是table爲空,那麼將threshold(擴容閾值)設置爲2的冪次方。
  • 若是table不爲空,若是map大小超過閾值,那麼就先擴容,而後循環調用putValue方法插入元素便可。 咱們從上面putMapEntries方法中看到,在插入節點的時候,都須要hash(key)計算出散列值,咱們看下源碼:

hash方法

/**
 * 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.'
 */
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
複製代碼

這個計算hash的方法設計的很是巧妙,下面咱們來詳細分析下這個過程:bootstrap

  • h=key.hashCode()。經過這一步先計算出Key鍵值類型自帶的哈希函數,返回int類型的散列值。
  • 將hashCode的高位參與運算,從新計算hash值。下面會解釋爲何須要h>>>16。

(n - 1) & hash來計算索引

咱們知道HashMap要想得到最好性能,就是計算的Hash值儘量的均勻分佈在每個桶中。理論上取模運算是一種分佈很均勻的算法。可是取模運算性能消耗仍是比較大的,在JDK8中,對取模運算進行了優化。經過位與運算來替代取模運算。理論公式是:x mod 2^n = x & (2^n - 1)。咱們知道HashMap底層數組的長度老是2的n次方,而且取模運算爲「h mod table.length」,對應上面的公式,能夠獲得該運算等同於「h & (table.length - 1)」。這是HashMap在速度上的優化,由於&比%具備更高的效率。數組

擾動函數

上面咱們在介紹hash計算的時候,看到h>>>16這樣的操做。爲何key的hashCode還須要使用高16位進行異或操做呢?bash

  • 咱們先假設沒有h>>>16這個操做。看看索引位置如何計算的 咱們假設HashMap桶的長度是默認值16.如今的索引計算以下:
10100101 11000100 00100101
& 00000000 00000000 00001111
----------------------------------
  00000000 00000000 00000101        //高位所有歸零,只保留末四位
複製代碼

但這時候問題就來了,這樣就算個人散列值分佈再鬆散,要是隻取最後幾位的話,碰撞也會很嚴重。更要命的是若是散列自己作得很差,分佈上成等差數列的漏洞,剛好使最後幾個低位呈現規律性重複,那麼碰撞就會更加嚴重。數據結構

  • 擾動函數的做用 上面提到過,只是使用最後幾位的話,碰撞會很嚴重,嚴重下降Map性能。若是咱們將高16位也加入運算,就能夠較好的解決問題。如圖:
    右位移16位,正好是32bit的一半,本身的高半區和低半區作異或,就是爲了混合原始哈希碼的高位和低位,以此來加大低位的隨機性(減小碰撞)。並且混合後的低位摻雜了高位的部分特徵,這樣高位的信息也被變相保留下來。

putVal方法

/**
 * 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;
}
複製代碼
  • 首先判斷table是否爲null或者size==0,若是還未初始化或者集合爲空,那麼先resize進行擴容。
  • 使用p = tab[i = (n - 1) & hash]方法定位到當前的桶在table中的索引。若是當前桶中沒有Node節點,那麼建立新的Node節點放入桶中便可。不然就說明當前桶中已有元素,須要遍歷鏈表。
  • else分支首先判斷第一個Node節點是不是符合條件的,若是是,整個查找過程就結束了。若是不是,判斷第一個節點是不是樹節點(這個桶是否已經樹化)。若是已經轉化成紅黑樹,就調用紅黑樹的插入操做。不然就是普通的鏈表遍歷操做。若是整個遍歷下來,都沒有找到符合條件的的Node節點的話,就構造一個Node節點,放入鏈表尾部便可,固然,若是鏈表的長度超過8,會調用treeifyBin方法將這個鏈表轉化爲紅黑樹。不然將找到的節點賦值給e便可。
  • 若是e不爲空的話,就說明Map中已有符合條件的節點,新的Value值能夠根據參數決定是否覆蓋舊值。
  • 最後size++,判斷節點數量是否超過threshold閾值,超過的話須要擴容。
  • 從源碼看出,Map中判斷一個元素是否相等是否的是==或者equal()方法。因此咱們在自定義類中,須要好好設計equal()方法和hashCode方法,由於這關乎到Map中元素的查找與比較。

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.
 *
 * @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;
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    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"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    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;
}
複製代碼
  • 首先根據擴容前的容量oldCap,若是oldCap容量已經到最大值了,那麼不進行擴容,只是將閾值設置爲Integer.MAX_VALUE。不然就是擴容爲原來的2倍。
  • 若是oldCap==0,可是oldThr不爲空的時候(由於構造HashMap初始容量被放入閾值),會將容量設置爲當前的閾值。
  • Map的容量和閾值都是0時,是一個空表,Map容量設置爲DEFAULT_INITIAL_CAPACITY大小(16)。並計算出閾值。
  • 若是新的閾值爲0,就根據新的容量和加載因子計算出新的閾值。
  • 開始遍歷老的Map集合,將裏面的Node節點從新定位到新的Map集合中。若是桶中只有一個元素,經過newTab[e.hash & (newCap - 1)] = e;計算出該Node在新Map中的索引便可。
  • 不然判斷該桶是否已經樹化,若是樹化,調用樹節點的方法進行hash分佈。不然就須要將鏈表數據一個個遍歷,從新定位。此處:HashMap的方法設計的很是精妙。經過定義loHead、loTail、hiHead、hiTail來說一個鏈表拆分紅兩個獨立的鏈表。注意:若是e的hash值與老表的容量進行與運算爲0,則擴容後的索引位置跟老表的索引位置同樣。因此loHead-->loTail組成的鏈表在新Map中的索引位置和老Map中是同樣的。若是e的hash值與老表的容量進行與運算爲1,則擴容後的索引位置爲:老表的索引位置+oldCap。
  • 最後將loHead、loTail、hiHead、hiTail組成的兩條鏈表從新定位到新的Map中便可。

擴容代碼(e.hash & oldCap)是否爲0來定位的問題

擴容代碼中,使用e節點的hash值跟oldCap進行位與運算,以此決定將節點分佈到原索引位置或者原索引+oldCap位置上,爲何能夠這樣計算,咱們來看例子:
假設老表的容量爲16,即oldCap=16,則新表容量爲16*2=32,假設節點1的hash值爲0000 0000 0000 0000 0000 1111 0000 1010,節點2的hash值爲0000 0000 0000 0000 0000 1111 0001 1010,則節點1和節點2在老表的索引位置計算以下圖計算1,因爲老表的長度限制,節點1和節點2的索引位置只取決於節點hash值的最後4位。再看計算2,計算2爲新表的索引計算,能夠知道若是兩個節點在老表的索引位置相同,則新表的索引位置只取決於節點hash值倒數第5位的值,而此位置的值恰好爲老表的容量值16,此時節點在新表的索引位置只有兩種狀況:原索引位置和原索引+oldCap位置(在此例中即爲10和10+16=26)。因爲結果只取決於節點hash值的倒數第5位,而此位置的值恰好爲老表的容量值16,所以此時新表的索引位置的計算能夠替換爲計算3,直接使用節點的hash值與老表的容量16進行位於運算,若是結果爲0則該節點在新表的索引位置爲原索引位置,不然該節點在新表的索引位置爲原索引+oldCap位置。 app

treeifyBin方法

/**
 * Replaces all linked nodes in bin at index for given hash unless
 * table is too small, in which case resizes instead.
 */
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);
    }
}
複製代碼

這個代碼是將鏈表轉化成紅黑樹的。咱們來看主要的邏輯:less

  • 若是Map的容量小於MIN_TREEIFY_CAPACITY(64)。是不會講某一個桶中的鏈表轉化爲紅黑樹的,會對Map進行擴容。這樣每個桶中的鏈表的長度會減小。
  • 若是Map的容量符合要求了,那就將鏈表轉化成紅黑樹。

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) { 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; } 複製代碼

HashMap是高效的查找數據結構,因此get方法咱們有必要好好分析下。ide

  • 首先計算出key的哈希值,而後使用first = tab[(n - 1) & hash])定位到索引位置。
  • 首先判斷第一個Node節點是不是符合要求的,符合要求就直接返回便可。不然判斷當前桶的結構是樹結構仍是鏈表結構,分別使用相關的方法尋找節點。沒有找到就返回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) {
    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) {
        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);
            }
        }
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}
複製代碼
  • 先根據key找到相應的節點,而後判斷須要刪除的節點是樹結構仍是鏈表結構。若是是樹結構調用removeTreeNode方法便可。鏈表的話只須要從新設置next節點便可。

總結

  • JDK8中HashMap的結構是數組+鏈表+紅黑樹的複合結構。
  • HashMap默認大小是16,加載因子0.75,能夠根據項目須要自定義加載因子。
  • HashMap的擴容操做是比較消耗時間的,若是能夠的話最好預估HashMap初始化的容量,以此來避免頻繁的擴容操做。
  • HashMap中鏈表轉化爲紅黑樹要知足兩個條件才行,第一:鏈表的長度已經達到8個了。第二:HashMap容量大於64便可。
  • HashMap中索引的定位和元素的查找,很是依賴key的hashCode和equal方法,咱們在自定義的類型的時候須要好好考慮如何比較兩個對象。
相關文章
相關標籤/搜索