1. 程式人生 > 其它 >HashMap原始碼分析記錄(JDK8)

HashMap原始碼分析記錄(JDK8)

技術標籤:hashmapjava

HashMap原始碼分析記錄

小白髮帖,如有錯誤,萬望斧正

HashMap繼承了AbstractMap,並實現了Map介面、Cloneable, Serializable介面,作為Map鍵值對稽核體系中最常用的一個實現類,允許空鍵和空值,不允許鍵重複,允許值重複,非執行緒安全。
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
}
* HashMap的資料結構:HashMap底層資料結構為可儲存連結串列或樹的Entry物件陣列,儲存鍵值對時,會對傳入的鍵進行hash運算,得到一個hash值,以此得到該鍵值對(Entry物件,在HashMap中是用其子類Node(K,V)儲存)存在物件陣列的哪個索引位置,當傳入的鍵值對的Key計算出的hash值與物件陣列中某個索引位置的鍵值對的Key的hash值相同,即為hash衝突,發生hash衝突後,HashMap會將後面的鍵值對以連結串列的形式加入到原有元素的後面,當連結串列長度達到7並且物件陣列容量達到64時,會將連結串列結構轉換為樹結構,以提高查詢的效能。當連結串列長度小於等於6時,又會將樹結構轉為連結串列結構。

1、成員變數

a、序列化Id:private static final long serialVersionUID = 362498820763181265L;

  private static final long serialVersionUID = 362498820763181265L;

b、預設初始容量DEFAULT_INITIAL_CAPACITY

 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

預設的初始容量為[16]

c、最大容量MAXIMUM_CAPACITY

  static final
int MAXIMUM_CAPACITY = 1 << 30;

最大容量限制為2^30

d、預設的負載係數DEFAULT_LOAD_FACTOR

 static final float DEFAULT_LOAD_FACTOR = 0.75f;

預設的負載係數為0.75,當Map中鍵值對個數大於當前容量的0.75時會進行擴容

e、當hash衝突時儲存的鍵值對由連結串列轉換為樹結構的判斷條件之一TREEIFY_THRESHOLD

 static final int TREEIFY_THRESHOLD = 8;

f、由樹結構轉為連結串列結構的閥值UNTREEIFY_THRESHOLD

 static
final int UNTREEIFY_THRESHOLD = 6;

g、連結串列結構轉換為樹結構的判斷條件之一MIN_TREEIFY_CAPACITY

static final int MIN_TREEIFY_CAPACITY = 64;

當陣列容量大於64且陣列中的連結串列節點大於8時會將連結串列結構轉換為樹結構,否則只會擴容

h、儲存鍵值對的物件陣列table

 transient Node<K,V>[] table;

i、快取鍵物件和值物件的Set集合entrySet

 transient Set<Map.Entry<K,V>> entrySet;

j、Map中儲存的鍵值對物件數size

transient int size;

k、修改因子modCount,每次修改(新增、刪除、移動、擴容、重新hash等)都會自增,用於實現fast-fail機制

 transient int modCount;

l、擴容閥值int threshold;是容量*負載係數的值,當容量達到大於該值時,會進行擴容並設定新的閥值

int threshold;

m、負載因子final float loadFactor;

 final float loadFactor;

2、內部類

a、儲存鍵值對的類Node<K,V>

//該類實現了Map介面的內部類Entry
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);
        }
	//修改鍵值對的V值
        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;
        }
    }

b、獲取Map的Key物件的類KeySet

 final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

c、獲取Key、Value值對映物件的類EntrySet

 final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Node<K,V> candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }
        public final boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }
        public final Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

3、構造方法

a、構造一個指定容量及負載係數的HashMap:public HashMap(int initialCapacity, float loadFactor)

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);
    //將傳入的負載因子賦值給成員變數裡的loadFactor
        this.loadFactor = loadFactor;
    //計算擴容閥值
        this.threshold = tableSizeFor(initialCapacity);
    }

b、構造一個指定容量的HashMap例項public HashMap(int initialCapacity)

 public HashMap(int initialCapacity) {
     //直接呼叫上面的方法,並將負載因子設定為預設的0.75
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

c、構造一個HashMap例項public HashMap()

public HashMap() {
    //使用預設負載因子
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

d、構造一個包含指定Map的HashMap例項public HashMap(Map<? extends K, ? extends V> m)

public HashMap(Map<? extends K, ? extends V> m) {
    //使用預設負載因子
        this.loadFactor = DEFAULT_LOAD_FACTOR;
    //呼叫存放Map集合的方法將傳入的集合新增到HashMap中
        putMapEntries(m, false);
    }

4、成員方法

a、計算hash雜湊的方法hash()

static final int hash(Object key) {
        int h;
    //根據傳入的鍵運用位運算來獲取衝突小的hash雜湊值並返回
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

b、擴容方法tableSizeFor

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

得到傳入的引數的兩倍並返回

c、將傳入的Map放到HashMap中 putMapEntries(Map<? extends K, ? extends V> m, boolean evict)

 final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            //如果HashMap為空,則計算擴容閥值
            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);
            }
            //原HashMap不為空,傳入的集合size大於擴容閥值,則進行擴容
            else if (s > threshold)
                resize();
            //遍歷傳入的集合,並將鍵值對放入原HashMap中
            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);
            }
        }
    }

d、返回對映中的鍵值對數public int size()

 public int size() {
        return size;
    }

e、判斷HashMap是否為空public boolean isEmpty()

public boolean isEmpty() {
        return size == 0;
    }

f、根據鍵獲取值get(K key)

  public V get(Object key) {
        Node<K,V> e;
      //獲取值
      //先獲取Node陣列的值,判斷是否為空,為空返回null,不為空返回value
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
//獲取Node陣列中元素的方法
 final Node<K,V> getNode(int hash, Object key) {
     //定義變數
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
     //判斷條件:Node鍵值對陣列不為空,陣列的length大於0,根據n-1&hash與運算得到的陣列索引的值不為空
        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);
            }
        }
     //都沒有則返回null
        return null;
    }

g、判斷HashMap是否包含傳入的鍵對應的對映public boolean containsKey(Object key)

 public boolean containsKey(Object key) {
     //呼叫此方法並判斷非空才返回ture
        return getNode(hash(key), key) != null;
    }

h、將鍵值對放入HashMap中public V put(K key, V value),如果key在HashMap中已存在,則會覆蓋該鍵所對應的value值

 public V put(K key, V value) {
     //呼叫方法
        return putVal(hash(key), key, value, false, true);
    }

//將鍵值對放入HashMap的Node陣列中的方法
 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
     //判斷Node陣列是否為空,為空則進行初始化擴容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
     //根據與運算得到的索引位置為空,則新建一個Node物件,放入該位置
        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;
            //如果Node陣列為樹結構,則將該鍵值對放到樹結構中
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //為連結串列結構,則迴圈
                for (int binCount = 0; ; ++binCount) {
                    //Node節點的下一個節點為空,則將傳入的鍵值對放入
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果連結串列長度大於等於樹結構轉換閥值減1,即7,則將對是否轉換為樹結構進行判斷
                        //如果Node陣列的容量小於等於64,則不轉換,否則將連結串列轉換為樹結構
                        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;
    }

i、擴容方法final Node<K,V>[] resize(),返回Node鍵值對陣列

 final Node<K,V>[] resize() {
     //將原陣列定義為oldTab
        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;
            }
            //新容量為原容量左移1位,即為原來的2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //新的擴容閥值也為原擴容閥值的2倍(左移1位)
                newThr = oldThr << 1; // double threshold
        }
     //如果原容量為0(即首次新增元素)
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            //將容量設定為預設容量16
            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;
                    //如果該Node上是樹結構,則會重新對結構進行判斷,新容量大於64且元素個數大於等於7,則還是採用樹結構儲存,否則轉換為連結串列
                    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;
    }

j、hash衝突時連結串列與樹結構轉換的判斷方法final void treeifyBin(Node<K,V>[] tab, int hash)

final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
 		//判斷陣列的容量是否大於等於64
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            //小於64,則進行擴容
            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);
        }
    }

k、將傳入的鍵值對集合放到HashMap中public void putAll(Map<? extends K, ? extends V> m)

 public void putAll(Map<? extends K, ? extends V> m) {
     //呼叫方法將集合元素放到HashMap中
        putMapEntries(m, true);
    }

l、移除傳入的鍵對應的鍵值對public V remove(Object key)

 public V remove(Object key) {
        Node<K,V> e;
     //返回移除的元素的value
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

//從Node鍵值對陣列中移除相對應的元素
 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;
    }

m、移除HashMap中所有的元素clear()

 public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

n、判斷HashMap是否包含傳入的value值得鍵值對public boolean containsValue(Object value)

public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null && size > 0) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

o、返回一個KeySet檢視public Set<K> keySet(),用於通過鍵取值等

 public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

p、移除HashMap中指定鍵值對元素public boolean remove(Object key, Object value)

 public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }

q、替換指定key的value值public boolean replace(K key, V oldValue, V newValue)

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

//替換的過載方法
 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;
    }