java.util系列源碼解讀之HashMap

Map是java中用于存儲建值對的一種數(shù)據(jù)結(jié)構(gòu)方式.鍵不能重復(fù), 每一個鍵可以匹配多個值(也就是一個鏈表).這個接口是用于替換Dictionary這個抽象類的.

HashMap用于存儲<key, value>鍵值對,其中key可以為null,同時他的key存放索引方式是通過hash方式來實現(xiàn)的,所以他能快速的定位到你需要的key處.在HashMap內(nèi)部是存放的一個Entry的數(shù)組.
Entry的定義如下:

Entry(int h, K k, V v, Entry<K,V> n) {
    value = v;
    next = n;
    key = k;
    hash = h;
}

類定義

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

成員變量

修飾符 變量名 作用
transient Entry<K,V>[] table table 存儲數(shù)據(jù)的內(nèi)部數(shù)組
static final Entry<?,?>[] EMPTY_TABLE 空數(shù)組, 用于初始化table
static final int MAXIMUM_CAPACITY = 1 << 30 map存放數(shù)據(jù)最大容量
static final int DEFAULT_INITIAL_CAPACITY = 16 map的默認(rèn)初始化容量
transient int size map的存儲數(shù)據(jù)大小,并不是table的length,而是Entry的數(shù)量
static final float DEFAULT_LOAD_FACTOR = 0.75f 默認(rèn)擴容因子,當(dāng)size/capacity>0.75時,map自動擴容同時執(zhí)行rehash
int threshold map要擴容到的大小
final float loadFactor map擴容因子,通過構(gòu)造方式傳入進(jìn)來
transient int modCount 記錄map的size變化次數(shù),跟list中的作用是一樣的
transient int hashSeed = 0 跟計算map的key索引hash值有關(guān),但是我也還沒明白(==補充:1.在resize()時判斷是否需要重新計算hash值;2.用于計算key的hash值==)

構(gòu)造方式

public HashMap()
無參構(gòu)造方式: 用默認(rèn)容量,默認(rèn)擴容因子構(gòu)造map

public HashMap(int initialCapacity)
用initialCapacity容量,默認(rèn)擴容因子構(gòu)造map

public HashMap(int initialCapacity, float loadFactor)
用initialCapacity容量,loadFactor擴容因子構(gòu)造map

public HashMap(Map<? extends K, ? extends V> m)
用其他map構(gòu)造新的map

核心方法

添加元素public V put(K key, V value)

public V put(K key, V value) {
    // 下面第一點講解
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    // 下面第二點講解
    if (key == null)
        return putForNullKey(value);
    
    // 取key的hash值,并用這個hash值來計算
    // 此鍵值對應(yīng)該放置的數(shù)組中的索引(bucketIndex)
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    
    // 根據(jù)key算出的索引,根據(jù)索引取得數(shù)組i處的Entry(鏈表)
    // 循環(huán)判斷此鏈表中是否存在此key對應(yīng)的節(jié)點
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        // 如果節(jié)點e的hash值與key的hash值相等(就是比較的hashCode),
        // 也就是說發(fā)生了hash碰撞(key的hashCode跟e.key的hashCode是同一值)
        // 并且key相等(同一位置或者equals),也就是key已經(jīng)存在對應(yīng)節(jié)點
        // 那么就執(zhí)行替換操作,并返回老的那個值
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }
    
    // 1. 如果數(shù)組索引i處沒有放置過任何值,也就是table[i]=null
    // 2. table[i]已經(jīng)放置了Entry,但是hash值不相等(不可能)或者是key不equals()
    // 則新增一個Entry節(jié)點
    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

代碼分析:

1. 如果當(dāng)前map中沒有任何元素,也就是說為空({}), 那么就重新擴充table,inflateTable()方法源碼如下:

private void inflateTable(int toSize) {
    // 將toSize向上取值到2的倍數(shù)
    int capacity = roundUpToPowerOf2(toSize);

    threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    table = new Entry[capacity];  // 重新給table賦值
    initHashSeedAsNeeded(capacity);  // 重新計算hashSeed值
}

2. 如果key為null,則專門處理key為null的情況,putForNullKey()代碼如下:

private V putForNullKey(V value) {
    // 從下述循環(huán)代碼可以看出, key為null的元素,
    // 在內(nèi)部數(shù)組中是放置在索引為0處位置的
    // (可能key不為null也會放置在這里,取決hash的結(jié)果如何)
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null) {  // 查找鏈表中key為null的節(jié)點,找到并用新值替換
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }
    
    // 如果在數(shù)組0處沒有找到key為null的對應(yīng)節(jié)點,則新增一個Entry節(jié)點
    modCount++;
    // key為null,hash直接取0,放置在數(shù)組中的位置也直接取0
    addEntry(0, null, value, 0);
    return null;
}

// 在數(shù)組索引bucketIndex處添加新的節(jié)點(注意是新增節(jié)點,并不一定是新增數(shù)組元素)
void addEntry(int hash, K key, V value, int bucketIndex) {
    // map當(dāng)前容量達(dá)到了要擴容的值并且數(shù)組中待放置節(jié)點的元素位置已被占用
    // 則擴容,并重新計算新的節(jié)點要放置在數(shù)組中的索引位置
    if ((size >= threshold) && (null != table[bucketIndex])) {
        resize(2 * table.length);
        hash = (null != key) ? hash(key) : 0;
        bucketIndex = indexFor(hash, table.length);
    }
    // 創(chuàng)建新的節(jié)點,并放置在數(shù)組中索引為buckedIndex處
    createEntry(hash, key, value, bucketIndex);
}

// 創(chuàng)建新的Entry節(jié)點(一個鏈表), 并將新的節(jié)點重新掛到數(shù)組上
// 在這里要注意的: bucketIndex的計算方式是怎么計算來的,在上面有講到
void createEntry(int hash, K key, V value, int bucketIndex) {
    // 獲取之前掛在數(shù)組bucketIndex處的Entry節(jié)點
    Entry<K,V> e = table[bucketIndex]; 
    // new Entry<>(hash, key, value, e);
    // 創(chuàng)建一個新的節(jié)點,并跟原來的節(jié)點建立關(guān)系
    table[bucketIndex] = new Entry<>(hash, key, value, e);
    size++;
}

獲取元素public V get(Object key)

public V get(Object key) {
    // key為null,專門處理
    if (key == null)
        return getForNullKey();  //取得數(shù)組0處的Entry
    Entry<K,V> entry = getEntry(key);

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

final Entry<K,V> getEntry(Object key) {
    // map中沒有元素返回null
    if (size == 0) {
        return null;
    }
    
    // 根據(jù)key的hash值取得對應(yīng)key存放在數(shù)組中的位置
    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;
}

擴容void resize(int newCapacity)
在put()等增加size的操作中調(diào)用, 在上述的addEntry()方法中被調(diào)用

void resize(int newCapacity) {
    // 如果map容量已經(jīng)達(dá)到Integer的最大值則不在擴容
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }
    
    // 創(chuàng)建一個擴容后的新的空數(shù)組
    Entry[] newTable = new Entry[newCapacity];
    // 將map現(xiàn)在數(shù)組轉(zhuǎn)移到新的空數(shù)組中
    // initHashSeedAsNeeded(newCapacity)用于確定在新數(shù)組
    // 每個key是否要重新計算hash值
    transfer(newTable, initHashSeedAsNeeded(newCapacity));
    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) {
    // 新數(shù)組的長度
    int newCapacity = newTable.length;
    // 對map中現(xiàn)有元素的老數(shù)組循環(huán)
    for (Entry<K,V> e : table) {
        // 取得的數(shù)組中元素不為空(對應(yīng)索引處存在Entry鏈表)
        while(null != e) {
            // 將鏈表的下一個節(jié)點拎出來保存
            Entry<K,V> next = e.next;
            // 是否需要重新計算key的hash值
            if (rehash) {
                e.hash = null == e.key ? 0 : hash(e.key);
            }
            // 重新計算在新數(shù)組中的索引
            int i = indexFor(e.hash, newCapacity);
            // 將已經(jīng)轉(zhuǎn)換到新數(shù)組的entry拼接到當(dāng)前處理entry的后面組成新的鏈表
            e.next = newTable[i];
            // 將新的鏈表重新放置在新數(shù)組的索引處
            newTable[i] = e;
            // 處理老數(shù)組鏈表的下一個entry
            e = next;
        }
    }
}

map迭代器Iterator核心private abstract class HashIterator<E>
map中的KeyIterator, ValueIterator等迭代器均繼承自HashIterator. map中的迭代器跟list中的迭代器一樣,都會根據(jù)size變化次數(shù)來fail-fast(快速失敗檢查)

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

    HashIterator() {
        expectedModCount = modCount; // 賦值modCount
        // map有元素,就定位數(shù)組索引到第一個不為null的位置,并賦給next
        if (size > 0) { // advance to first entry
            Entry[] t = table;
            while (index < t.length && (next = t[index++]) == null)
                ;
        }
    }

    public final boolean hasNext() {
        return next != null;
    }

    final Entry<K,V> nextEntry() {
        // 在迭代期間, modCount值發(fā)生變化
        // (也就是map的size發(fā)生改變(執(zhí)行了put, remove操作(迭代器的remove()除外)))
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        Entry<K,V> e = next;
        if (e == null)
            throw new NoSuchElementException();
        // 繼續(xù)判斷下一個entry,如果為空,則繼續(xù)搜索數(shù)組下一個索引位置
        if ((next = e.next) == null) {
            Entry[] t = table;
            while (index < t.length && (next = t[index++]) == null)
                ;
        }
        // 返回當(dāng)前的entry
        current = e;
        return e;
    }
    
    // 用迭代器執(zhí)行刪除操作(不會引起快速失敗)
    public void remove() {
        if (current == null)
            throw new IllegalStateException();
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        Object k = current.key;
        current = null;
        HashMap.this.removeEntryForKey(k);
        expectedModCount = modCount;
    }
}

針對map常見面試問題

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容