HashMap源代碼

HashMap是最常使用的類,所以學習它的源碼很重要。

HashMap的結構如下:


/**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

由Entry[] table負責存儲數據。其中Entry是它的靜態內部類,Entry結構如下:

static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;
很明顯可以看出,Entry就是一個鏈表,所以HashMap的結構其實就是一個數組,然後數組裏面的元素是鏈表,如下圖所示:


HashMap中最常使用的方法是get和put,首先看下put方法

public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)//允許null key
            return putForNullKey(value);
        int hash = hash(key);//對key進行hash
        int i = indexFor(hash, table.length);//通過hash值找到對應存儲位置
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {//遍歷鏈元素,查找鏈表中有沒有相同的key,如果有就替換
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {//先比較hash,如果hash值相等,再比較具體的key值
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);//如果沒有key,就做插入
        return null;
    }

private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {//大體過程與普通put操作一樣,只不過要注意如果是null key就存儲在0位置
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }

get方法:

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

        return null == entry ? null : entry.getValue();
    }
private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {//沒什麼好說的,就要注意null key的值存儲在0位置
            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);//再次證明null key 在0位置
        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;
    }






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