HashMap

本文主要記錄閱讀HashMap源碼的過程java

一、HashMap的JavaDoc

HashMap APInode

HashMap類位於JDK的java.util包api

整體思路:數組

    每個key,value對,以node對象存放在連續的數組中,hash值相同的key以鏈表的形式存放在同一個index處(jdk8以後,若是同一個index下的node節點數大於8時,將以紅黑樹的形式存放,這樣將提升查詢效率)。oracle

二、類圖

JDK1.8app


 

 

成員變量this

大寫的成員變量都是finalspa

DEFAULT_INITIAL_CAPACITY:默認容量,必須是2的冪,初始值爲16code

MAXIMUM_CAPACITY:最大容量,2的30次方對象

DEFAULT_LOAD_FACTOR:加載因子,0.75(不知道是爲何取值爲0.75)

TREEIFY_THRESHOLD:閾值8(這是jdk8以後才添加的,表示hashmap中某個桶中的節點數大於該值時,存儲結構將由原來的鏈表結構變爲紅黑樹結構)

Node<K,V>  存放在數組中的節點類型;

 

三、關鍵操做

對象構造

注意:全部的代碼都來自於jdk1.8

注意:在構造hashmap對象時,不會爲table分配內存,table的內存分配在put操做時進行

一、不指定任何參數,此時全部屬性均按照初始值;

二、構造方法指定map的大小m,並不必定會分配m大小的內存給table,由於capacity必須是2的冪,須要經過以下代碼設置

 1 static final int tableSizeFor(int cap) {
 2 
 3     int n = cap -1;
 4 
 5     n |= n >>>1;
 6 
 7     n |= n >>>2;
 8 
 9     n |= n >>>4;
10 
11     n |= n >>>8;
12 
13     n |= n >>>16;
14 
15     return (n <0) ?1 : (n >=MAXIMUM_CAPACITY) ?MAXIMUM_CAPACITY : n +1;
16 
17 }

 

hash值計算

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

將key的hashcode的高16位和低16位作異或操做,按照代碼中的註釋解釋說是爲了減少hash衝突。

 

put操做

調用putVal,代碼以下:

代碼註釋是本身添加

hashmap的桶中元素多是Node,或者treenode,若是元素較少,則使用鏈表存儲,若是元素較多,則改成紅黑樹存儲

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)// 若是是第一次put操做,table爲null,則爲其分配默認capacity大小的空間,resize返回的值必定是2的冪
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)//n-1的二進制是全爲1,==null表示該桶爲空,若是不爲空,把桶中鏈表第一個元素(或者紅黑樹root)
            tab[i] = newNode(hash, key, value, null);//桶中第一個元素,採用鏈表形式,所以用newNode
        else {//桶中已經有其餘元素,hash碰撞
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))//若是put的key已經存在
                e = p;
            else if (p instanceof TreeNode)//若是p是紅黑樹節點,則插入一個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))))//若是遍歷過程當中,某個元素的key與須要put的key同樣則break
                        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;//修改次數計數+1,執行到這裏表示put的key是最新的,否則上面的if就已經返回了return oldValue;
	  if (++size > threshold)//若是hashmap的總元素大於閾值,則擴容
            resize();
        afterNodeInsertion(evict);
        return null;
}

 

擴容操做reSize

reSize除了擴展空間以外,還須要將原有的數據轉移到新申請的內存空間

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//存放原有的capacity
        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)//原有的hashmap中,該桶只有一個元素
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)//若是該桶中元素是樹節點,
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);//把樹節點拆分到新map中的不一樣桶中
                    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;
    }

 

get操做:這個方法相對簡單,不作過多閱讀

remove操做

public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

調用removeNode方法

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) {//首先須要remove的節點必須存在,不然返回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;
    }
相關文章
相關標籤/搜索