理解HashMap,HashTable-基於java1.8


title: “理解HashMap-基於java1.8”

url: “https://wsk1103.github.io/

tags:

  • Java

java -version :jdk 1.8.0_191

HashMap

構造

image

類內參數,方法

image

image

image

實現

image
基於數組 + 鏈表實現。

當單條鏈表的個數達到8個時候,鏈表就會被轉換成紅黑樹

鏈表時間複雜度O(n),紅黑樹時間複雜度O(log n)

靜態參數

    /**
     * The default initial capacity - MUST be a power of two.
     */
    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;
    數組的最大值,2^30。
    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    默認負載因子,當新增的key在Map中超過 (Map中key的數量 * 負載因子) 的時候,就會擴容。
    擴容是比較耗內存的,所以設計的時候,很多時候都要考慮一下Map的大小,防止頻繁擴容或者佔用無畏的空間。
    /**
     * 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;
    當單個鏈表裏面的key個數超過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;
    
    //超過這個值則以翻倍形式擴容(resize)
    //threshold = capacity * load factor
    int threshold;
    map的閾值

put 方法

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

在存入到HashMap的時候,需要先計算一下hash值,然後根據hash值存放到對應的數組和鏈表中。

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

函數作用:高16bit不變,低16bit和高16bit做了一個異或

假設 h = hashCode() = 1111 1111 1111 1111 1111 0101 1010 0011

步數 操作
1 h = hashCode() 1111 1111 1111 1111 1111 0101 1010 0011
2 h 1111 1111 1111 1111 1111 0101 1010 0011
3 h >>> 16 0000 0000 0000 0000 1111 1111 1111 1111
4 h ^ (h >>> 16) 1111 1111 1111 1111 0000 1010 0101 1100
5 (n - 1) & hash 0000 0000 0000 0000 0000 0000 0000 1111(15)
1111 1111 1111 1111 0000 1010 0101 1100
6 結果 1100(12)

則結果 (n - 1) & hash 值爲12。

可以看出,HashMap是允許key爲null的,當key爲null的時候,hash值爲0。

注意:當key存放是一個對象的時候,一般情況下我們需要重寫這個對象的hashCode()方法,防止嚴重碰撞,或者鏈表/紅黑樹過長。

    /**
     * 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;
        if ((tab = table) == null || (n = tab.length) == 0)
            //重置HashMap
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            //當數組tab中對應的位置爲空,則直接存放到該tab[]中。
            //i = (n - 1) & hash 取模定位數組位置
            tab[i] = newNode(hash, key, value, null);
        else {
            //已經存在該key的hash值或者碰撞衝突。
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                // 已經存在,保存起來,用於返回oldValue
                e = p;
            else if (p instanceof 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);
                        //當列表個數超過8個的時候,轉換成紅黑樹。
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //已經存在該key
                    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;
                //當參數onlyIfAbsent設置爲false的時候,即使相同的key,也不插入。
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);//這個沒有什麼用,空方法
                return oldValue;
            }
        }
        //修改的次數,該值用transient修飾,無法被序列號.
        ++modCount;
        //當key的數量超過閾值時,翻倍並重新將key插入一個新的map中。
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);//這個沒有什麼用,空方法
        return null;
    }

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

get方法也是用hash值,快速定位到具體的數組位置。

    /**
     * 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))))
                // 找到hash值相等 和 key也相等
                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;
    }

resize方法

擴容

每次擴容都需要重新分配數組,並把老的值再分配到新的數組,耗能比較高,所以應該儘量避免擴容。例如在初始化的時候,判斷該Map的key的數量可以會達到最大的數值,Map map = new HashMap(keyNum);

    /**
     * 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;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                //當數組tab的個數超過2^32的時候,已經不需要做什麼了。
                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;
        //開始將舊的值存到新的map中
        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提供4中初始化的構造器

1. 參數 int initialCapacity, float loadFactor

initialCapacity:初始map的數組大小
loadFactor:負載因子

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    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);
    }

2. 參數int initialCapacity

initialCapacity:初始map的數組大小

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

3. 無參

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

4. 參數 Map<? extends K, ? extends V> m

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

循環遍歷Map

map.forEach((key,value)->{
    System.out.println("key=" + key + " value=" + value);
});

其他說明

HashMap 和 HashTable 區別

  • HashMap是unsynchronized,使用的時候要注意線程安全。
  • HashMap允許key爲null,而HashTable不允許key爲null。
  • HashTable線程安全的原理是在操作Map的方法上都加入synchronized。

HashMap 和 ConcurrentHashMap 區別

  • HashMap是unsynchronized,使用的時候要注意線程安全。
  • ConcurrentHashMap是synchronized,多線程的情況下,直接使用這個。
  • ConcurrentHashMap 的原理是在操作每個數組對應的位置加鎖,而不是整個Map加鎖,所以性能比HashTabe好。

Fail-Fast機制

在多個線程同時操作同一個Map的時候,每次修改map,則modCount++,當檢測到modCount發生改變的時候,則拋出異常 throw new ConcurrentModificationException();

取模

如果數組tab的長度爲n,如果要對hash進行取模,一般的做法是

hash % n

但是HashMap的取模是

hash & (n - 1)

因爲n在初始化的時候,我們會把n定義爲2的次冪,所以n-1 的二進制是01111111…

hash & n-1 實際上就是取保留低位值,結果是在n的範圍內,類似取模運算。

假設 n = 16,hash = 1111 1111 1111 1111 1111 0101 1010 0011

步數 計算
1 n -1 0000 0000 0000 0000 0000 0000 0000 0111(15)
2 hash 1111 1111 1111 1111 1111 0101 1010 0011
3 hash & n-1 0000 0000 0000 0000 0000 0000 0000 0011(3)

當時當在初始化數組的時候,沒有設置爲2的次冪,那麼就和一般的取模運算一樣,沒有什麼性能改進。

使HashMap線程安全

如果不使用ConcurrentHashMap,那麼可以使用java.util包。

Map m = Collections.synchronizedMap(new HashMap(...));

同時Set,List也一樣。

HashTable

實現的接口和繼承的類和 HashMap 一致,裏面的方法,變量的定義也是基本一致的。
只是在操作數組和鏈表的時候,在所有的方法上都添加 synchronized 關鍵字。

例如 add方法

    /**
     * Maps the specified <code>key</code> to the specified
     * <code>value</code> in this hashtable. Neither the key nor the
     * value can be <code>null</code>. <p>
     *
     * The value can be retrieved by calling the <code>get</code> method
     * with a key that is equal to the original key.
     *
     * @param      key     the hashtable key
     * @param      value   the value
     * @return     the previous value of the specified key in this hashtable,
     *             or <code>null</code> if it did not have one
     * @exception  NullPointerException  if the key or value is
     *               <code>null</code>
     * @see     Object#equals(Object)
     * @see     #get(Object)
     */
    public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

從這裏就可以看出, HashTable 是不允許存儲的對象爲 null

並且 HashTable 中的鏈表是不會轉爲紅黑樹。

有趣的是, HashTable 的初始容量是 11,而 擴容操作int newCapacity = (oldCapacity << 1) + 1 ,即*2+1 ,
計算hash也比較簡單

int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章