JDK1.7 HashMap 兩張圖一句話,剩下全靠編

JDK1.7 HashMap一探究竟

爲了對的起大家百兆寬帶,所有的筆記都已經上傳至
【碼雲】 ,歡迎大家star或者fork
點個【star】 在走

HashMap很簡單,原理一看散列表,實際數組+鏈表;Hash找索引.索引若爲null,while下一個.Hash對對碰,鏈表依次查.加載因子.75,剩下無腦擴數組.

開局兩張圖,剩下全靠編

JDK1.7的HashMap

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable
  • AbstractMap<k,V> 對一些簡單的功能的實現
  • Map接口,定義了一組通用的Map操作的方法
  • Cloneable接口,可以拷貝
  • Serializable 可序列化

定義的常量

   static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 默認初始化大小 10000B
    static final int MAXIMUM_CAPACITY = 1 << 30; //最大的容量 2的20次方 
    static final float DEFAULT_LOAD_FACTOR = 0.75f; //影響因子 0.75 影響因子是哈希表在其容量自動增加之前可以達到多滿的一種尺度。當哈希表中的條目 數超出了加載因子與當前容量的乘積時,通過調用 rehash 方法將容量翻倍。
    static final Entry<?,?>[] EMPTY_TABLE = {};// 字面意思哈希表的入口數組.
    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE; //表示在對字符串鍵(即key爲String類型)的HashMap應用備選哈希函數時HashMap的條目數量的默認閾值。備選哈希函數的使用可以減少由於對字符串鍵進行弱哈希碼計算時的碰撞概率。

定義的變量

    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;  //不可序列化的哈希表,初始化爲上面空的哈希表 
    transient int size; //哈希表中存儲的數據  
    int threshold; // 下次擴容的臨界值,size>=threshold就會擴容
    final float loadFactor;  //影響因子
    transient int modCount; //修改的次數  
    private static class Holder {...} //它的作用是在虛擬機啓動後根據jdk.map.althashing.threshold和ALTERNATIVE_HASHING_THRESHOLD_DEFAULT初始化ALTERNATIVE_HASHING_THRESHOLD
    transient int hashSeed = 0;  //seed 種子值 

HashMap的構造方法

    public HashMap(int initialCapacity, float loadFactor){
         this.loadFactor = loadFactor;
        threshold = initialCapacity; //threshold  下次擴容的臨界值也設置爲  initialCapacity
        init(); //一個空方法的實現  
    }
 public HashMap(int initialCapacity){
      this(initialCapacity, DEFAULT_LOAD_FACTOR);
 }
  public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }
  public HashMap(Map<? extends K, ? extends V> m) { //用Map初始化
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        inflateTable(threshold);

        putAllForCreate(m); //通過forEach,將複製到新的HashMap中  
    }
Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY) //保證了map構成新的HashMap的時候容量,計算Factor後小於對應的默認因子.

真正存放鍵值的內部類

   static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next; //一個典型的鏈表的實現.單向鏈表 
        int hash;

        // 構造函數 
        Entry(int h, K k, V v, Entry<K,V> n) { 
            value = v;
            next = n;
            key = k;
            hash = h;
        }
        //... 一些比較普遍方法的實現 
        //Entry中的自己的Hash的實現 
        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }
    }

哈希的計算方法

   final int hash(Object k) {
        int h = hashSeed; //h爲Hash的隨機種子值 
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        } //生成對應字符串的哈希值 

        h ^= k.hashCode(); //hashCode之後異或

        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12); //最前面的12位和最後面的12位進行異或. 在與h異或,得到仍是一個32位的值
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

計算存儲下標(indexFor)

    /**
     * Returns index for hash code h.
     */
    static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1); //對hash進行與運算,得到對應的存儲的下標
    }

get方法的實現

    public V get(Object key) {
        if (key == null) //對應鍵爲null的情況
            return getForNullKey();
            //普通的情況 
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }

對null鍵處理的函數

這是一個私有方法,方便其他函數的調用

    private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }

獲得鍵值對

    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

put方法

 public V put(K key, V value) {
      if (table == EMPTY_TABLE) {
            inflateTable(threshold); //inflateTable方法就是建立哈希表,分配表內存空間的操作(inflate翻譯爲“膨脹”的意思,後面會詳述)。但是指定初始容量和負載因子的構造方法並沒有馬上調用inflateTable。
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {//出現重複的值會覆蓋
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;

put中的子方法addEntry

    void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);// 容器當前存放的鍵值對數量是否達到了設定的擴容閾值,如果達到了就擴容2倍。擴容後重新計算哈希碼,並根據新哈希碼和新數組長度重新計算存儲位置。做好潛質處理後,就調用createEntry新增一個Entry
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
    }

transfer 方法 實現鏈表的擴容中的具體複製

  void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length; //擴容後的處理
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;  //鏈表成爲了倒序
            }
        }
    } 

addEntry 中的createEntry方法

    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex]; //入口
        table[bucketIndex] = new Entry<>(hash, key, value, e); //讓該節點替代入口地址,原來的鏈表連接在後面.就是所謂的頭插法
        size++;
    }

對 threshold的處理

鏈表的容量擴充爲2的冪次. 調整 threshold 方法

 private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize); //實現了增長爲2的冪運算. 實現也比較簡單

        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    }

HashMap的遍歷

上面HashMap的基本操作已經完成了.下面就是一些對於Iterator接口的實現

    private abstract class HashIterator<E> implements Iterator<E> {
        Entry<K,V> next;        // next entry to return
        int expectedModCount;   // For fast-fail
        int index;              // current slot
        Entry<K,V> current;     // current entry
    }

Fail-Fast 機制
我們知道 java.util.HashMap 不是線程安全的,因此如果在使用迭代器的過程中有其他線程修改了map,那麼將拋出ConcurrentModificationException,這就是所謂fail-fast策略。這一策略在源碼中的實現是通過 modCount 域,modCount 顧名思義就是修改次數,對HashMap 內容的修改都將增加這個值,那麼在迭代器初始化過程中會將這個值賦給迭代器的 expectedModCount。在迭代過程中,判斷 modCount 跟 expectedModCount 是否相等,如果不相等就表示已經有其他線程修改了 Map:注意到 modCount 聲明爲 volatile,保證線程之間修改的可見性。

構造方法

    HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ; //在Hash計算的時候會有部分的表爲空,找到一個不爲空的值 
            }
        }

hasNext() 和 nextEntry()

       public final boolean hasNext() {
            return next != null; //第一次判斷的是否不爲空
        }

        final Entry<K,V> nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ; //同樣利用循環找到寫一個對應的鏈表節點  
            }
            current = e;
            return e;
        }

關於多線程的問題

假設線程A和線程B對一個共享的HashMap同時put一個值. put後發現需要擴容,擴容後進行內存拷貝執行transfer方法.那麼必定出現循環鏈表.以後get() 的時候出現死循環.

參考博客

理解HashMap 老哥寫的比我好

【碼雲】 中國人自己的gitHub,不看一看

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章