HashMap 介紹

基本介紹

1. 用於存儲Key-Value鍵值對的集合(每個鍵值對也叫作一個Entry)(無順序)。

2. 根據鍵的hashCode值存儲數據,大多數狀況下能夠直接定位到它的值。

3. 鍵key爲null的記錄至多隻容許一條,值value爲null的記錄能夠有多條。

4. 非線程安全。

5. HashMap是由數組+鏈表+紅黑樹(JDK1.8後增長了紅黑樹部分,鏈表長度超過閾值(8)時會將鏈表轉換爲紅黑樹)實現的。

6. HashMap與Hashtable區別:
        Hashtable是synchronized的。
        Hashtable不能夠接受爲null的鍵值(key)和值(value)。

數組 + 鏈表 + 紅黑樹

1. 數組是用來肯定桶的位置(尋址容易,插入和刪除困難):
        數組的查找效率比LinkedList大。
        HashMap中數組擴容恰好是2的次冪,在作取模運算的效率高,而ArrayList的擴容機制是1.5倍擴容。

2. 鏈表是用來解決hash衝突問題,當出現hash值同樣的情形,就在數組上的對應位置造成一條鏈表(尋址困難,插入和刪除容易)(鏈地址法)。

3. 鏈表轉爲紅黑樹:
        當元素小於8個當時候,此時作查詢操做,鏈表結構已經能保證查詢性能。
        當元素大於8個的時候,此時須要紅黑樹來加快查詢速度,可是新增節點的效率會變慢。

4. 當鏈表轉爲紅黑樹後,元素個數是6會退化爲鏈表:
        中間有個差值7能夠防止鏈表和樹之間頻繁的轉換。

key必須是不變的類

防止key發生變化,致使沒法取出value。


自定義不可變類:

    不提供改變成員變量的方法,包括setter

    在getter方法中,不要直接返回對象自己,而是克隆對象,並返回對象的拷貝

public final class Immutable {

    private final int[] myArray;    //防止直接修改myArray內容

    public Immutable(int[] array) {
        this.myArray = array.clone();    //若是直接將array賦值給myArray,是引用變量,array的內容變化則myArray的內容也會變化
    }

    public int[] getMyArray() {
        return myArray.clone();
    }
}

HashMap的擴容機制

生成hash:

    異或運算(減小了碰撞的概率):(h = key.hashCode()) ^ (h >>> 16)

    原來的 hashCode:1111 1111 1111 1111 0100 1100 0000 1010
    移位後的hashCode:0000 0000 0000 0000 1111 1111 1111 1111
    進行異或運算結果:1111 1111 1111 1111 1011 0011 1111 0101

    這樣作的好處是,能夠將hashcode高位和低位的值進行混合作異或運算,並且混合後,低位的信息中加入了高位的信息,
    這樣高位的信息被變相的保留了下來。摻雜的元素多了,那麼生成的hash值的隨機性會增大。


HashMap的擴容是申請一個容量爲原數組大小兩倍的新數組:
    遍歷舊數組,從新計算每一個元素的索引位置,並複製到新數組中。
    由於HashMap的哈希桶數組大小老是爲2的冪次方,So從新計算後的索引位置要麼在原來位置不變,要麼就是「原位置+舊數組長度」。

擴充HashMap:
    複製數組元素及肯定索引位置時不須要從新計算hash值,
    只須要判斷原來的hash值新增的那個bit是1,仍是0:
        若爲0,則索引未改變;
        若爲1,則索引變爲「原索引+舊數組長度」


threshold和loadFactor兩個屬性決定着是否擴容:
    threshold=Length*loadFactor,Length表示table數組的長度(默認值爲16),loadFactor爲負載因子(默認值爲0.75)
    閥值threshold表示當table數組中存儲的元素個數超過該閥值時,即須要擴容。

源碼分析

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {

    private static final long serialVersionUID = 362498820763181265L;

    //默認的初始容量是16,必須是2的冪。
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //最大容量(必須是2的冪且小於2的30次方,傳入容量過大將被這個值替換)
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //默認加載因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //閾值:用來肯定什麼時候鏈表轉爲紅黑樹
    static final int TREEIFY_THRESHOLD = 8;

    //用來肯定什麼時候紅黑樹轉變爲鏈表
    static final int UNTREEIFY_THRESHOLD = 6;

    //當想要將解決hash衝突的鏈表轉變爲紅黑樹時,須要判斷此時數組的容量,
    //如果數組容量過小(64),則不進行鏈表轉爲紅黑樹的操做,而是利用resize()函數對HashMap擴容
    static final int MIN_TREEIFY_CAPACITY = 64;

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

    //減小了碰撞(key的hash值相等)的概率
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    /**
     * 數組Table的每個元素不單純只是一個Entry對象,它仍是一個鏈表的頭節點:
     *      每個Entry對象經過Next指針指向下一個Entry節點。
     *      當新來的Entry映射到衝突數組位置時,只須要插入對應的鏈表位置便可。
     */
    transient Node<K,V>[] table;

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

    //實際存儲的key-value鍵值對的個數
    transient int size;

    //HashMap發生結構性變化的次數(value值的覆蓋不屬於結構性變化)
    transient int modCount;

    //threshold的值="容量*加載因子",當HashMap中存儲數據的數量達到threshold時,就須要將HashMap的容量加倍。
    int threshold;

    //加載因子實際大小
    final 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);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    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是否已初始化,不然進行初始化table操做
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //根據hash值肯定節點在數組中的插入的位置,即計算索引存儲的位置,若該位置無元素則直接進行插入
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //節點若已經存在元素,即待插入位置存在元素
            Node<K,V> e; K k;
            //判斷已存在的元素與待插入元素的hash值和key值是否相等,若是相等則將此節點賦值給e,便於後續覆蓋value。
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //判斷該元素是否爲紅黑樹節點
            else if (p instanceof TreeNode)
                //紅黑樹節點則調用putTreeVal()函數進行插入
                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);
                        //若鏈表上節點超過TREEIFY_THRESHOLD - 1,即鏈表長度爲8,將鏈表轉變爲紅黑樹
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //判斷已存在的元素與待插入元素的hash值和key值是否相等,若是相等則將此節點賦值給e,便於後續覆蓋value。
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //當key存在時,覆蓋value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                //若存在key節點,則更新此節點的value,並返回舊的value。
                return oldValue;
            }
        }
        //記錄修改次數
        ++modCount;
        //判斷是否須要擴容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        //若不存在key節點(插入新key),則返回null
        return null;
    }

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    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 = null; 釋放HashMap對象,裏面所引用的對象也釋放了。
    // HashMap.clear(); 釋放HashMap對象儲存的全部對象。
    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;
        }
    }

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

    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;
        //判斷表是否爲空,以及p節點根據鍵的hash值對應到數組的索引初是否有節點
        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;
            //如果須要刪除的節點就是該頭節點,則讓node引用指向它
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            //結點在當前p所指向的頭節點的鏈表或紅黑樹中,須要遍歷查找
            else if ((e = p.next) != null) {
                //若頭節點是紅黑樹節點,則調用紅黑樹自己的遍歷方法getTreeNode,獲取待刪除的結點
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                //不然就是普通鏈表,則使用do while循環遍歷查找待刪除結點
                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)))) {
                //如果紅黑樹結點的刪除,則直接調用紅黑樹的removeTreeNode方法進行刪除
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //若待刪除結點是一個頭節點,則用它的next節點頂替它做爲頭節點存放在table[index]中,以此達到刪除的目的
                else if (node == p)
                    tab[index] = node.next;
                //若待刪除結點爲普通鏈表中的一個結點,則用該節點的前一個節點直接跳過該待刪除節點,指向它的next結點
                else
                    p.next = node.next;
                //記錄修改次數
                ++modCount;
                --size;
                afterNodeRemoval(node);
                //若removeNode方法刪除成功則返回被刪除的結點
                return node;
            }
        }
        //若沒有刪除成功則返回null
        return null;
    }

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

相關文章
相關標籤/搜索