1. 程式人生 > >java集合原始碼解析:map

java集合原始碼解析:map

map裡面用的最多的就是HashMap了, 如果需要對key進行排序的話,會用到 TreeMap

先看看HashMap的原始碼

HashMap內部還是用陣列的方式實現的

transient Node<K,V>[] table;
//Node的定義,除了key,value外,hash用來確定在陣列中的位置. Node陣列中每個元素其實是個連結串列(連結串列長度超過8則轉為紅黑樹)結構,當有hash衝突時,這個連結串列中就會存放有相同hash值的節點,
//next用來表示其在連結串列(紅黑樹)中的下一個節點
    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;
        }
    }

當使用put方法新增元素時,需要先根據hashcode確定在陣列中的位置,然後找出此位置的節點,然後插入這個節點對應的連結串列(紅黑樹)中

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
	//在put時需要先判斷map是否為空,如果為空則需要用resize()進行擴容,jdk1.6中會在new HashMap() 時對陣列進行初始化,但是jdk1.8中則不會,直接將初始化的操作放在了put方法裡面
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
	//這裡先根據Node的hash值來計算在陣列中的索引"i",如果tab[i]為空則直接插入這個位置
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
	//如果不為空,則說明有了相同的hash值,如果key也相同,那麼直接覆蓋現有元素,如果沒有相同的key,說明hash值有了衝突,需要將這個Node放在此處對應的連結串列(紅黑樹)中
        else {
            Node<K,V> e; K k;
	//有對應的key,直接覆蓋
            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 {//如果還不是紅黑樹,那麼則是一個連結串列,遍歷連結串列中的資料,如果有相同的key則替換,沒有則放到連結串列結尾
                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 連結串列長度超過8,連結串列轉換為紅黑樹
                            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;
    }
hashmap預設容量為16,預設載入因子為0.75, 當map裡面的內容超過容量*載入因子時,就需要對map進行擴容操作,避免產生過多的hash衝突

使用resize()擴容時,會擴容為原來長度的2倍,jdk1.8之前進行擴容需要重新計算整個map的hash值,jdk1.8進行了優化

在resize()的註釋中我們可以看到 must either stay at same index, or move with a power of two offset in the new table, 一部分保持原來位置,另一部分則會根據原位置再移動2次冪(比如原來下標是15,總長度是16,現在擴容長度變為32,那麼原來15位置的節點,部分不變,另一部分會移動到15+16=31的位置),具體的可以看resize()的程式碼:

    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 計算新的容量,左移一位,變為原來長度的2倍
        }
        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;
    }

hashmap在get時,只需要先根據hash值獲取對應的下標,然後遍歷對應的連結串列或者紅黑樹,找到對應的value即可

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
TreeMap則可以根據key進行排序,每個節點都是一個紅黑樹,紅黑樹比一般的二叉搜尋樹要複雜的多,以後有空再研究下吧
Hashtable跟HashMap的實現基本類似,Hashtable不允許key 為null,而HashMap則可以, Hashtable也是執行緒安全的,在方法上都加了synchronized

而collection裡面的HashSet 和 TreeSet則是直接依賴了HashMap和TreeMap,將map裡面的可以作為集合元素(與value無關,value = new Object())