1. 程式人生 > >Hi, 我是佛系碼農 Ted

Hi, 我是佛系碼農 Ted

HashMap實現原理

 HashMap的主幹是一個Entry陣列。Entry是HashMap的基本組成單元,每一個Entry包含一個key-value鍵值對。

//HashMap的主幹陣列,可以看到就是一個Entry陣列,初始值為空陣列{},主幹陣列的長度一定是2的次冪,至於為什麼這麼做,後面會有詳細分析。
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

 Entry是HashMap中的一個靜態內部類。程式碼如下

複製程式碼
    static class Entry<K,V> implements
Map.Entry<K,V> { final K key; V value; Entry<K,V> next;//儲存指向下一個Entry的引用,單鏈表結構 int hash;//對key的hashcode值進行hash運算後得到的值,儲存在Entry,避免重複計算
    </span></span><span style="color: #008000;">/**</span><span style="color: #008000;">
     * Creates new entry.
     </span><span style="color: #008000;">*/</span><span style="color: #000000;">
    Entry(</span><span style="color: #0000ff;">int</span> h, K k, V v, Entry&lt;K,V&gt;<span style="color: #000000;"> n) {
        value </span>=<span style="color: #000000;"> v;
        next </span>=<span style="color: #000000;"> n;
        key </span>=<span style="color: #000000;"> k;
        hash </span>=<span style="color: #000000;"> h;
    }</span>&nbsp;</pre>
複製程式碼

 所以,HashMap的整體結構如下

  簡單來說,HashMap由陣列+連結串列組成的,陣列是HashMap的主體,連結串列則是主要為了解決雜湊衝突而存在的,如果定位到的陣列位置不含連結串列(當前entry的next指向null),那麼對於查詢,新增等操作很快,僅需一次定址即可;如果定位到的陣列包含連結串列,對於新增操作,其時間複雜度為O(n),首先遍歷連結串列,存在即覆蓋,否則新增;對於查詢操作來講,仍需遍歷連結串列,然後通過key物件的equals方法逐一比對查詢。所以,效能考慮,HashMap中的連結串列出現越少,效能才會越好。

其他幾個重要欄位

複製程式碼
//實際儲存的key-value鍵值對的個數
transient int size; //閾值,當table == {}時,該值為初始容量(初始容量預設為16);當table被填充了,也就是為table分配記憶體空間後,threshold一般為 capacity*loadFactory。HashMap在進行擴容時需要參考threshold,後面會詳細談到 int threshold; //負載因子,代表了table的填充度有多少,預設是0.75 final float loadFactor; //用於快速失敗,由於HashMap非執行緒安全,在對HashMap進行迭代時,如果期間其他執行緒的參與導致HashMap的結構發生變化了(比如put,remove等操作),需要丟擲異常ConcurrentModificationException transient int modCount;
複製程式碼

HashMap有4個構造器,其他構造器如果使用者沒有傳入initialCapacity 和loadFactor這兩個引數,會使用預設值

initialCapacity預設為16,loadFactory預設為0.75

我們看下其中一個

複製程式碼
public HashMap(int initialCapacity, float loadFactor) {     //此處對傳入的初始容量進行校驗,最大不能超過MAXIMUM_CAPACITY = 1<<30(230)
        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);
    </span><span style="color: #0000ff;">this</span>.loadFactor =<span style="color: #000000;"> loadFactor;
    threshold </span>=<span style="color: #000000;"> initialCapacity;<br>     
    init();<span style="color: #008000;">//init方法在HashMap中沒有實際實現,不過在其子類如 linkedHashMap中就會有對應實現</span>
}</span></pre>
複製程式碼

  從上面這段程式碼我們可以看出,在常規構造器中,沒有為陣列table分配記憶體空間(有一個入參為指定Map的構造器例外),而是在執行put操作的時候才真正構建table陣列

  OK,接下來我們來看看put操作的實現吧

複製程式碼
    public V put(K key, V value) {
        //如果table陣列為空陣列{},進行陣列填充(為table分配實際記憶體空間),入參為threshold,此時threshold為initialCapacity 預設是1<<4(24=16)
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
       //如果key為null,儲存位置為table[0]或table[0]的衝突鏈上
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);//對key的hashcode進一步計算,確保雜湊均勻
        int i = indexFor(hash, table.length);//獲取在table中的實際位置
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        //如果該對應資料已存在,執行覆蓋操作。用新value替換舊value,並返回舊value
            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++;//保證併發訪問時,若HashMap內部結構發生變化,快速響應失敗
        addEntry(hash, key, value, i);//新增一個entry
        return null;
    }    
複製程式碼

 先來看看inflateTable這個方法

複製程式碼
private void inflateTable(int toSize) {
        int capacity = roundUpToPowerOf2(toSize);//capacity一定是2的次冪
        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);//此處為threshold賦值,取capacity*loadFactor和MAXIMUM_CAPACITY+1的最小值,capaticy一定不會超過MAXIMUM_CAPACITY,除非loadFactor大於1
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    }
複製程式碼

  inflateTable這個方法用於為主幹陣列table在記憶體中分配儲存空間,通過roundUpToPowerOf2(toSize)可以確保capacity為大於或等於toSize的最接近toSize的二次冪,比如toSize=13,則capacity=16;to_size=16,capacity=16;to_size=17,capacity=32.

按 Ctrl+C 複製程式碼按 Ctrl+C 複製程式碼

roundUpToPowerOf2中的這段處理使得陣列長度一定為2的次冪,Integer.highestOneBit是用來獲取最左邊的bit(其他bit位為0)所代表的數值.

hash函式

複製程式碼
//這是一個神奇的函式,用了很多的異或,移位等運算,對key的hashcode進一步進行計算以及二進位制位的調整等來保證最終獲取的儲存位置儘量分佈均勻
final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }
    h </span>^=<span style="color: #000000;"> k.hashCode();

    h </span>^= (h &gt;&gt;&gt; 20) ^ (h &gt;&gt;&gt; 12<span style="color: #000000;">);
    </span><span style="color: #0000ff;">return</span> h ^ (h &gt;&gt;&gt; 7) ^ (h &gt;&gt;&gt; 4<span style="color: #000000;">);
}</span></pre>
複製程式碼

以上hash函式計算出的值,通過indexFor進一步處理來獲取實際的儲存位置

複製程式碼
  /**
     * 返回陣列下標
     */
    static int indexFor(int h, int length) {
        return h & (length-1);
    }
複製程式碼

h&(length-1)保證獲取的index一定在陣列範圍內,舉個例子,預設容量16,length-1=15,h=18,轉換成二進位制計算為

        1  0  0  1  0
    &   0  1  1  1  1
    __________________
        0  0  0  1  0    = 2

  最終計算出的index=2。有些版本的對於此處的計算會使用 取模運算,也能保證index一定在陣列範圍內,不過位運算對計算機來說,效能更高一些(HashMap中有大量位運算)

所以最終儲存位置的確定流程是這樣的:

再來看看addEntry的實現:

複製程式碼
void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);//當size超過臨界閾值threshold,並且即將發生雜湊衝突時進行擴容
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
    createEntry(hash, key, value, bucketIndex);
}</span></pre>
複製程式碼

  通過以上程式碼能夠得知,當發生雜湊衝突並且size大於閾值的時候,需要進行陣列擴容,擴容時,需要新建一個長度為之前陣列2倍的新的陣列,然後將當前的Entry陣列中的元素全部傳輸過去,擴容後的新陣列長度為之前的2倍,所以擴容相對來說是個耗資源的操作。

三、為何HashMap的陣列長度一定是2的次冪?

我們來繼續看上面提到的resize方法

複製程式碼
 void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }
    Entry[] newTable </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> Entry[newCapacity];
    transfer(newTable, initHashSeedAsNeeded(newCapacity));
    table </span>=<span style="color: #000000;"> newTable;
    threshold </span>= (<span style="color: #0000ff;">int</span>)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1<span style="color: #000000;">);
}</span></pre>
複製程式碼

如果陣列進行擴容,陣列長度發生變化,而儲存位置 index = h&(length-1),index也可能會發生變化,需要重新計算index,我們先來看看transfer這個方法

複製程式碼
void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;     //for迴圈中的程式碼,逐個遍歷連結串列,重新計算索引位置,將老陣列資料複製到新陣列中去(陣列不儲存實際資料,所以僅僅是拷貝引用而已)
        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);          //將當前entry的next鏈指向新的索引位置,newTable[i]有可能為空,有可能也是個entry鏈,如果是entry鏈,直接在連結串列頭部插入。
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }
複製程式碼

  這個方法將老陣列中的資料逐個連結串列地遍歷,扔到新的擴容後的陣列中,我們的陣列索引位置的計算是通過 對key值的hashcode進行hash擾亂運算後,再通過和 length-1進行位運算得到最終陣列索引位置。

  hashMap的陣列長度一定保持2的次冪,比如16的二進位制表示為 10000,那麼length-1就是15,二進位制為01111,同理擴容後的陣列長度為32,二進位制表示為100000,length-1為31,二進位制表示為011111。從下圖可以我們也能看到這樣會保證低位全為1,而擴容後只有一位差異,也就是多出了最左位的1,這樣在通過 h&(length-1)的時候,只要h對應的最左邊的那一個差異位為0,就能保證得到的新的陣列索引和老陣列索引一致(大大減少了之前已經雜湊良好的老陣列的資料位置重新調換),個人理解。

  

 還有,陣列長度保持2的次冪,length-1的低位都為1,會使得獲得的陣列索引index更加均勻,比如:

  我們看到,上面的&運算,高位是不會對結果產生影響的(hash函式採用各種位運算可能也是為了使得低位更加雜湊),我們只關注低位bit,如果低位全部為1,那麼對於h低位部分來說,任何一位的變化都會對結果產生影響,也就是說,要得到index=21這個儲存位置,h的低位只有這一種組合。這也是陣列長度設計為必須為2的次冪的原因。

  如果不是2的次冪,也就是低位不是全為1此時,要使得index=21,h的低位部分不再具有唯一性了,雜湊衝突的機率會變的更大,同時,index對應的這個bit位無論如何不會等於1了,而對應的那些陣列位置也就被白白浪費了。

get方法

複製程式碼
 public V get(Object key) {     //如果key為null,則直接去table[0]處去檢索即可。
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);
        return null == entry ? null : entry.getValue();
 }
複製程式碼

get方法通過key值返回對應value,如果key為null,直接去table[0]處檢索。我們再看一下getEntry這個方法

複製程式碼
final Entry<K,V> getEntry(Object key) {
    </span><span style="color: #0000ff;">if</span> (size == 0<span style="color: #000000;">) {
        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">null</span><span style="color: #000000;">;
    }
    </span><span style="color: #008000;">//</span><span style="color: #008000;">通過key的hashcode值計算hash值</span>
    <span style="color: #0000ff;">int</span> hash = (key == <span style="color: #0000ff;">null</span>) ? 0<span style="color: #000000;"> : hash(key);
    </span><span style="color: #008000;">//</span><span style="color: #008000;">indexFor (hash&amp;length-1) 獲取最終陣列索引,然後遍歷連結串列,通過equals方法比對找出對應記錄</span>
    <span style="color: #0000ff;">for</span> (Entry&lt;K,V&gt; e =<span style="color: #000000;"> table[indexFor(hash, table.length)];
         e </span>!= <span style="color: #0000ff;">null</span><span style="color: #000000;">;
         e </span>=<span style="color: #000000;"> e.next) {
        Object k;
        </span><span style="color: #0000ff;">if</span> (e.hash == hash &amp;&amp; <span style="color: #000000;">
            ((k </span>= e.key) == key || (key != <span style="color: #0000ff;">null</span> &amp;&amp;<span style="color: #000000;"> key.equals(k))))
            </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> e;
    }
    </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">null</span><span style="color: #000000;">;
}    </span></pre>
複製程式碼

  可以看出,get方法的實現相對簡單,key(hashcode)-->hash-->indexFor-->最終索引位置,找到對應位置table[i],再檢視是否有連結串列,遍歷連結串列,通過key的equals方法比對查詢對應的記錄。要注意的是,有人覺得上面在定位到陣列位置之後然後遍歷連結串列的時候,e.hash == hash這個判斷沒必要,僅通過equals判斷就可以。其實不然,試想一下,如果傳入的key物件重寫了equals方法卻沒有重寫hashCode,而恰巧此物件定位到這個陣列位置,如果僅僅用equals判斷可能是相等的,但其hashCode和當前物件不一致,這種情況,根據Object的hashCode的約定,不能返回當前物件,而應該返回null,後面的例子會做出進一步解釋。

四、重寫equals方法需同時重寫hashCode方法

  關於HashMap的原始碼分析就介紹到這兒了,最後我們再聊聊老生常談的一個問題,各種資料上都會提到,“重寫equals時也要同時覆蓋hashcode”,我們舉個小例子來看看,如果重寫了equals而不重寫hashcode會發生什麼樣的問題

複製程式碼
/**
 * Created by chengxiao on 2016/11/15.
 */
public class MyTest {
    private static class Person{
        int idCard;
        String name;
    </span><span style="color: #0000ff;">public</span> Person(<span style="color: #0000ff;">int</span><span style="color: #000000;"> idCard, String name) {
        </span><span style="color: #0000ff;">this</span>.idCard =<span style="color: #000000;"> idCard;
        </span><span style="color: #0000ff;">this</span>.name =<span style="color: #000000;"> name;
    }
    @Override
    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">boolean</span><span style="color: #000000;"> equals(Object o) {
        </span><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span> ==<span style="color: #000000;"> o) {
            </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #000000;">;
        }
        </span><span style="color: #0000ff;">if</span> (o == <span style="color: #0000ff;">null</span> || getClass() !=<span style="color: #000000;"> o.getClass()){
            </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #000000;">;
        }
        Person person </span>=<span style="color: #000000;"> (Person) o;
        </span><span style="color: #008000;">//</span><span style="color: #008000;">兩個物件是否等值,通過idCard來確定</span>
        <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">this</span>.idCard ==<span style="color: #000000;"> person.idCard;
    }

}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> main(String []args){
    HashMap</span>&lt;Person,String&gt; map = <span style="color: #0000ff;">new</span> HashMap&lt;Person, String&gt;<span style="color: #000000;">();
    Person person </span>= <span style="color: #0000ff;">new</span> Person(1234,"喬峰"<span style="color: #000000;">);
    </span><span style="color: #008000;">//</span><span style="color: #008000;">put到hashmap中去</span>
    map.put(person,"天龍八部"<span style="color: #000000;">);
    </span><span style="color: #008000;">//</span><span style="color: #008000;">get取出,從邏輯上講應該能輸出“天龍八部”</span>
    System.out.println("結果:"+map.get(<span style="color: #0000ff;">new</span> Person(1234,"蕭峰"<span style="color: #000000;">)));
}

}

複製程式碼

實際輸出結果:

結果:null

  如果我們已經對HashMap的原理有了一定了解,這個結果就不難理解了。儘管我們在進行get和put操作的時候,使用的key從邏輯上講是等值的(通過equals比較是相等的),但由於沒有重寫hashCode方法,所以put操作時,key(hashcode1)-->hash-->indexFor-->最終索引位置 ,而通過key取出value的時候 key(hashcode1)-->hash-->indexFor-->最終索引位置,由於hashcode1不等於hashcode2,導致沒有定位到一個數組位置而返回邏輯上錯誤的值null(也有可能碰巧定位到一個數組位置,但是也會判斷其entry的hash值是否相等,上面get方法中有提到。)

  所以,在重寫equals的方法的時候,必須注意重寫hashCode方法,同時還要保證通過equals判斷相等的兩個物件,呼叫hashCode方法要返回同樣的整數值。而如果equals判斷不相等的兩個物件,其hashCode可以相同(只不過會發生雜湊衝突,應儘量避免)。