1. 程式人生 > >HashMap原理-1.7

HashMap原理-1.7

ria 裝載 get方法 非線程安全 factor sun off tom dentry

之所以分兩篇文章記錄,因為之前一直看的1.7的源碼,而且網上很多的都是關於1.7的,今天在1.8上打開源碼一看,居然懵了。 沒想到1.8的實現變化這麽大。所有特地拿一篇文章來記錄下。

本章只介紹1.7的情況

1.HashMap存儲結構

技術分享

哈希表是由數組+鏈表組成的,一個長度為16的數組中,每個元素存儲的是一個鏈表的頭結點。那麽這些元素是按照什麽樣的規則存儲到數組中呢。一般情況是通過hash(key)%len獲得,也就是元素的key的哈希值對數組長度取模得到。比如上述哈希表中,12%16=12,28%16=12,108%16=12,140%16=12。所以12、28、108以及140都存儲在數組下標為12的位置。當下標有沖突的時候,就需要解決沖突,目前解決沖突的方法有:

  1. 開放定址法(線性探測再散列,二次探測再散列,偽隨機探測再散列)
  2. 再哈希法
  3. 鏈地址法
  4. 建立一個公共溢出區

Java中的hashmap的解決辦法就是采用的鏈地址法。

源碼分析

數據結構

/**
* The table, resized as necessary. Length MUST Always be a power of two.,長度必須為2的指數次,為什麽?其中非常重要的原因就是為了hash的平均分布
*/
transient Entry<K,V>[] table; //定義table數組,類型為Entry
static class Entry<K,V> implements Map.Entry<K,V> {  //entry,即鏈表結構,存放key,value,next節點
final K key;
V value;
Entry<K,V> next;
int hash;

2.HashMap put方法

打個比方, 第一個鍵值對A進來,通過計算其key的hash得到的index=0,記做:Entry[0] = A。一會後又進來一個鍵值對B,通過計算其index也等於0,現在怎麽辦?HashMap會這樣做:B.next = A,Entry[0] = B,如果又進來C,index也等於0,那麽C.next = B,Entry[0] = C;這樣我們發現index=0的地方其實存取了A,B,C三個鍵值對,他們通過next這個屬性鏈接在一起。所以疑問不用擔心。也就是說數組中存儲的是最後插入的元素。

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value); //空值的put,放到index0的位置
    int hash = hash(key);
    int i = indexFor(hash, table.length); //獲取Hash值對應的數組index
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {  //獲取數組index的entry,如果不為空則尋找下一個節點,直到到entry為null
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { //如果key相同,則替換key的value,或者
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i); //添加元素
    return null;
}

void addEntry(int hash, K key, V value, int bucketIndex) {
    if ((size >= threshold) && (null != table[bucketIndex])) {  //如果超過裝載因子的最大值,則需要對數組進行擴容
        resize(2 * table.length);
        hash = (null != key) ? hash(key) : 0;
        bucketIndex = indexFor(hash, table.length);  //獲取hash對應的新的index
    }

    createEntry(hash, key, value, bucketIndex); //創建entry
}

/**
 * Like addEntry except that this version is used when creating entries
 * as part of Map construction or "pseudo-construction" (cloning,
 * deserialization).  This version needn‘t worry about resizing the table.
 *
 * Subclass overrides this to alter the behavior of HashMap(Map),
 * clone, and readObject.
 */
void createEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];  //將當前數組index的節點保存
    table[bucketIndex] = new Entry<>(hash, key, value, e);  //數組index的值更新為新節點,之前的節點變為新節點的next節點;
    size++;
}

  

3.HashMap get方法

    public V get(Object key) {
        if (key == null)
            return getForNullKey();  //null值獲取
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }
    final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key); //求key的hash值
        for (Entry<K,V> e = table[indexFor(hash, table.length)]; //在數組中查找hash值對應的下標
             e != null;
             e = e.next) {//如果entry不為null的情況下,繼續遍歷鏈表的下一個節點,直到查找到key相同,且hash值相同的,返回搜索結果
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

/**
     * Offloaded version of get() to look up null keys.  Null keys map
     * to index 0.  This null case is split out into separate methods
     * for the sake of performance in the two most commonly used
     * operations (get and put), but incorporated with conditionals in
     * others.
     */
    private V getForNullKey() {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }

4.HashMap擴容

/**
* Rehashes the contents of this map into a new array with a
* larger capacity. This method is called automatically when the
* number of keys in this map reaches its threshold.
*
* If current capacity is MAXIMUM_CAPACITY, this method does not
* resize the map, but sets threshold to Integer.MAX_VALUE.
* This has the effect of preventing future calls.
**/
void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {  //判斷是否達到最大容量
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
        boolean oldAltHashing = useAltHashing;
        useAltHashing |= sun.misc.VM.isBooted() &&
                (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean rehash = oldAltHashing ^ useAltHashing;
        transfer(newTable, rehash); //擴容,將原來的數據添加到新的數組中
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

    /**
     * Transfers all entries from current table to newTable.
     */
    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;
            }
        }
    }

  

5.HashMap缺點

a.不支持多線程,即非線程安全;

HashMap原理-1.7