1. 程式人生 > >JDK1.8 HashMap原始碼分析

JDK1.8 HashMap原始碼分析

JDK1.8  HashMap原始碼分析

一、HashMap概述

JDK1.8之前,HashMap採用陣列+連結串列實現,即使用連結串列處理衝突,同一hash值的連結串列都儲存在一個連結串列裡。但是當位於一個桶中的元素較多,即hash值相等的元素較多時,通過key值依次查詢的效率較低。而JDK1.8中,HashMap採用陣列+連結串列+紅黑樹實現,當連結串列長度超過閾值(8)時,將連結串列轉換為紅黑樹,這樣大大減少了查詢時間。

下圖中代表jdk1.8之前的hashmap結構,左邊部分即代表雜湊表,也稱為雜湊陣列,陣列的每個元素都是一個單鏈表的頭節點,連結串列是用來解決衝突的,如果不同的key對映到了陣列的同一位置處,就將其放入單鏈表中。(此圖借用網上的圖)


圖一、jdk1.8之前hashmap結構圖

jdk1.8之前的hashmap都採用上圖的結構,都是基於一個數組和多個單鏈表,hash值衝突的時候,就將對應節點以連結串列的形式儲存。如果在一個連結串列中查詢其中一個節點時,將會花費O(n)的查詢時間,會有很大的效能損失。到了jdk1.8,當同一個hash值的節點數不小於8時,不再採用單鏈表形式儲存,而是採用紅黑樹,如下圖所示(此圖是借用的圖)

圖二、jdk1.8 hashmap結構圖

二、重要的field

//table就是儲存Node類的陣列,就是對應上圖中左邊那一欄,
  /**
     * 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;
	
/**
     * The number of key-value mappings contained in this map.
*  記錄hashmap中儲存鍵-值對的數量
  */
transient int size;

/**
  * hashmap結構被改變的次數,fail-fast機制
  */
transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     * 擴容的門限值,當size大於這個值時,table陣列進行擴容
     */
    int threshold;

    /**
     * The load factor for the hash table.
     *
     */
 float loadFactor;
/**
     * The default initial capacity - MUST be a power of two.
* 預設初始化陣列大小為16
     */
    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;


三、建構函式

//可以自己指定初始容量和裝載因子
    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;
		//先移位再或運算,最終保證返回值是2的整數冪
        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;
    }

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

    //將map直接放入hashmap中
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

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


/**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedMyHashMap for its Entry subclass.)
     */
	在hashMap的結構圖中,hash陣列就是用Node型陣列實現的,許多Node類通過next組成連結串列,key、value實際儲存在Node內部類中。
    public 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;
        }
    }


四、重要的方法分析

1.put方法


/**
     * Associates the specified value with the specified key in thismap.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
*/
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
static final int hash(Object key) {
        int h;
		//key的值為null時,hash值返回0,對應的table陣列中的位置是0
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

/**
     * 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;
//先將table賦給tab,判斷table是否為null或大小為0,若為真,就呼叫resize()初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
//通過i = (n - 1) & hash得到table中的index值,若為null,則直接新增一個newNode
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
		//執行到這裡,說明發生碰撞,即tab[i]不為空,需要組成單鏈表或紅黑樹
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
//此時p指的是table[i]中儲存的那個Node,如果待插入的節點中hash值和key值在p中已經存在,則將p賦給e
                e = p;
//如果table陣列中node類的hash、key的值與將要插入的Node的hash、key不吻合,就需要在這個node節點連結串列或者樹節點中查詢。
            else if (p instanceof TreeNode)
			//當p屬於紅黑樹結構時,則按照紅黑樹方式插入
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
	//到這裡說明碰撞的節點以單鏈表形式儲存,for迴圈用來使單鏈表依次向後查詢
                for (int binCount = 0; ; ++binCount) {
		//將p的下一個節點賦給e,如果為null,建立一個新節點賦給p的下一個節點
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
		//如果衝突節點達到8個,呼叫treeifyBin(tab, hash),這個treeifyBin首先回去判斷當前hash表的長度,如果不足64的話,實際上就只進行resize,擴容table,如果已經達到64,那麼才會將衝突項儲存結構改為紅黑樹。

                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
//如果有相同的hash和key,則退出迴圈
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;//將p調整為下一個節點
                }
            }
//若e不為null,表示已經存在與待插入節點hash、key相同的節點,hashmap後插入的key值對應的value會覆蓋以前相同key值對應的value值,就是下面這塊程式碼實現的
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
		//判斷是否修改已插入節點的value
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;//插入新節點後,hashmap的結構調整次數+1
        if (++size > threshold)
            resize();//HashMap中節點數+1,如果大於threshold,那麼要進行一次擴容
        afterNodeInsertion(evict);
        return null;
    }
2.擴容函式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;//定義臨時Node陣列型變數,作為hash table
		//讀取hash table的長度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;//讀取擴容門限
        int newCap, newThr = 0;//初始化新的table長度和門限值
        if (oldCap > 0) {
			//執行到這裡,說明table已經初始化
            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
		//用構造器初始化了門限值,將門限值直接賦給新table容量
            newCap = oldThr;
        else {              
 // zero initial threshold signifies using defaults
//老的table容量和門限值都為0,初始化新容量,新門限值,在呼叫hashmap()方式構造容器時,就採用這種方式初始化
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
			//如果門限值為0,重新設定門限
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;//更新新門限值為threshold
        @SuppressWarnings({"rawtypes","unchecked"})
	   //初始化新的table陣列
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
		//當原來的table不為null時,需要將table[i]中的節點遷移
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
				//取出連結串列中第一個節點儲存,若不為null,繼續下面操作
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;//主動釋放
                    if (e.next == null)
	//連結串列中只有一個節點,沒有後續節點,則直接重新計算在新table中的index,並將此節點儲存到新table對應的index位置處
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
					//若e是紅黑樹節點,則按紅黑樹移動
                        ((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 {
//下面這段暫時沒有太明白,通過e.hash & oldCap將連結串列分為兩隊,參考知乎上的一段解釋
/**
* 把連結串列上的鍵值對按hash值分成lo和hi兩串,lo串的新索引位置與原先相同[原先位
* j],hi串的新索引位置為[原先位置j+oldCap];
* 連結串列的鍵值對加入lo還是hi串取決於 判斷條件if ((e.hash & oldCap) == 0),因為* capacity是2的冪,所以oldCap為10...0的二進位制形式,若判斷條件為真,意味著
* oldCap為1的那位對應的hash位為0,對新索引的計算沒有影響(新索引
* =hash&(newCap-*1),newCap=oldCap<<2);若判斷條件為假,則 oldCap為1的那位* 對應的hash位為1,
* 即新索引=hash&( newCap-1 )= hash&( (oldCap<<2) - 1),相當於多了10...0,
* 即 oldCap

* 例子:
* 舊容量=16,二進位制10000;新容量=32,二進位制100000
* 舊索引的計算:
* hash = xxxx xxxx xxxy xxxx
* 舊容量-1 1111
* &運算 xxxx
* 新索引的計算:
* hash = xxxx xxxx xxxy xxxx
* 新容量-1 1 1111
* &運算 y xxxx
* 新索引 = 舊索引 + y0000,若判斷條件為真,則y=0(lo串索引不變),否則y=1(hi串
* 索引=舊索引+舊容量10000)
   */

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


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



/**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }


4.紅黑樹

/**
     * Entry for Tree bins. Extends LinkedMyHashMap.Entry (which in turn
     * extends Node) so can be used as extension of either regular or
     * linked node.
     */
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        //紅黑樹暫時還沒有仔細研究,紅黑樹相關的增刪改查操作後期再認真分析。


五、總結

仔細分析hashmap原始碼後,可以掌握很多常用的資料結構的用法。本次筆記只是記錄了hashmap幾個常用的方法,像紅黑樹、迭代器等還沒有仔細研究,後面有時間會認真分析。

http://wenku.baidu.com/link?url=AHcaJRmJofOxRbX6L8vKoYSW59Tl-GJexJjNUdEvHuAwDgRtPfCzHhVTO21v7BV0V-OTp7D0BC3sh2jdctV9RYnwhM_6w8SlZ9Np-cago-7

相關推薦

JDK1.8 HashMap原始碼分析 ----轉載別人的,以後好複習。

本人看不懂原始碼,邏輯思維差,又懶。連看文件都喜歡跳字閱讀。所以只能去看別人寫的原始碼分析。也不知道能不能轉載。。所以直接貼個地址。 這是幾天下來,翻了好多篇部落格,發現寫的非常詳細,而且步驟和註釋寫的非常清晰的一篇了。。 大神好厲害。拜讀兩遍,以表敬意。 讀技

jdk1.8 HashMap原始碼分析(resize函式)

final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.len

JDK1.8 HashMap原始碼分析

JDK1.8  HashMap原始碼分析 一、HashMap概述 在JDK1.8之前,HashMap採用陣列+連結串列實現,即使用連結串列處理衝突,同一hash值的連結串列都儲存在一個連結串列裡。但是當位於一個桶中的元素較多,即hash值相等的元素較多時,通過key值依次查

JDK1.8 HashMap原始碼解析(不分析紅黑樹部分)

一、HashMap資料結構        HashMap由 陣列+連結串列+紅黑樹實現,桶中元素可能為連結串列,也可能為紅黑樹。為了提高綜合(查詢、新增、修改)效率,當桶中元素數量超過TREEIFY_THRESHOLD(預設為8)時,連結串列儲存改為紅黑樹儲存,當桶中元素數量

JDK1.8 ConcurrentHashMap原始碼分析

文章目錄 ConcurrentHashMap資料結構 類的繼承關係 類的內部類 重要的屬性 類的建構函式 ConcurrentHashMap()型建構函式 ConcurrentHashMap(i

Jdk1.7 HashMap原始碼分析與思考

HashMap類圖 根據類圖可知,HashMap實現了三個介面繼承了一個抽象類。 實現的介面概覽 介面如下: java.util.Map 其中Map介面中定義了Map基本操作方法,詳細介面描述請參考java.util.Map介面描述. Map介面中採

LinkedList(JDK1.8原始碼分析

雙向迴圈連結串列 雙向迴圈連結串列和雙向連結串列的不同在於,第一個節點的pre指向最後一個節點,最後一個節點的next指向第一個節點,也形成一個“環”。而LinkedList就是基於雙向迴圈連結串列設計的。 LinkedList 的繼承關係 LinkedList 是一個繼承於AbstractSeq

java集合之----HashMap原始碼分析(基於JDK1.7與1.8

一、什麼是HashMap 百度百科這樣解釋: 簡而言之,HashMap儲存的是鍵值對(key和value),通過key對映到value,具有很快的訪問速度。HashMap是非執行緒安全的,也就是說在多執行緒併發環境下會出現問題(死迴圈) 二、內部實現 (1)結構 HashM

通俗易懂的JDK1.8HashMap原始碼分析(歡迎探討指正)+ 典型面試題

面試題在最下面 說到HashMap之前,閱讀ArrayList與LinkedList的原始碼後做個總結 ArrayList 底層是陣列,查詢效率高,增刪效率低 LinkedList底層是雙鏈表,查詢效率低,增刪效率高   這裡只是總結看完原始碼後對hashm

HashMap原始碼分析-jdk1.6和jdk1.8的區別

在java集合中,HashMap是用來存放一組鍵值對的數,也就是key-value形式的資料,而在jdk1.6和jdk1.8的實現有所不同。 JDK1.6的原始碼實現: 首先來看一下HashMap的類的定義: HashMap繼承了AbstractHashMap,實現

HashMap原始碼分析(JDK1.8)

一、HashMap簡介  基於雜湊表的 Map 介面的實現。此實現提供所有可選的對映操作,並允許key和value為null(但是隻能有一個key為null,且key不能重複,value可以重複)。(除了非同步和允許使用 null 之外,HashMap 類與 Hashtab

HashMap原始碼分析JDK1.8)- 你該知道的都在這裡了

       HashMap是Java和Android程式設計師的基本功, JDK1.8對HashMap進行了優化, 你真正理解它了嗎? 考慮如下問題:  1、雜湊基本原理?(答:散列表、hash碰撞、連結串列、紅黑樹)2、hashmap查詢的時間複雜度, 影響因素和原理?

java集合(4):HashMap原始碼分析jdk1.8

前言 Map介面雖然也是集合體系中的重要一個分支,但是Map介面並不繼承自Collection,而是自成一派。 public interface Map<K,V> Map集合儲存鍵對映到值的物件。一個集合中不能包含重複的鍵,每個鍵最多

HashMap原始碼分析jdk1.8

private static final long serialVersionUID = 362498820763181265L;      //The default initial capacity - MUST be a power of two. static final 

HashMap 原始碼分析(JDK1.8)

0 概述 HashMap是Java程式設計師使用頻率最高的容器之一,主要原因它的查詢效率比較高,本文基於JDK1.8,深入探討HashMap的結構實現和功能原理。 1 HashMap底層資料結構 首先看下HashMap底層資料結構,本質上就是一個數組+連結

基於jdk1.8HashMap原始碼分析(溫故學習)

鼎力推薦一下一. HashMap結構      HashMap在jdk1.6版本採用陣列+連結串列的儲存方式,但是到1.8版本時採用了陣列+連結串列/紅黑樹的方式進行儲存,有效的提高了查詢時間,解決衝突。這裡有一篇部落格寫的非常好,HashMap的結構圖也畫的非常清楚,鼎力推

Jdk1.8下的HashMap原始碼分析

**目錄結構** 一、面試常見問題 二、基本常量屬性 三、構造方法 四、節點結構        4.1 Node類        4.2.TreeNode 五、put方法

Java中HashMap底層實現原理(JDK1.8)源碼分析

blank imp dash logs || 屬性 lte das ces 這幾天學習了HashMap的底層實現,但是發現好幾個版本的,代碼不一,而且看了Android包的HashMap和JDK中的HashMap的也不是一樣,原來他們沒有指定JDK版本,很多文章都是舊版本J

【集合框架】JDK1.8源碼分析HashMap(一) 轉載

.get 修改 object set implement .com 功能 數組元素 帶來 一、前言   在分析jdk1.8後的HashMap源碼時,發現網上好多分析都是基於之前的jdk,而Java8的HashMap對之前做了較大的優化,其中最重要的一個優化就是桶中

jdk1.8 HashMap源碼分析(resize函數)

進入 這樣的 hit mil 二次 函數 1.8 參數初始化 是否 // 擴容兼初始化 final Node<K, V>[] resize() { Node<K, V>[] oldTab = table; i