Android HashMap源碼分析

類前注釋:

/**
 * HashMap is an implementation of {@link Map}. All optional operations are supported.
 *
 * <p>All elements are permitted as keys or values, including null.
 *
 * <p>Note that the iteration order for HashMap is non-deterministic. If you want
 * deterministic iteration, use {@link LinkedHashMap}.
 *
 * <p>Note: the implementation of {@code HashMap} is not synchronized.
 * If one thread of several threads accessing an instance modifies the map
 * structurally, access to the map needs to be synchronized. A structural
 * modification is an operation that adds or removes an entry. Changes in
 * the value of an entry are not structural changes.
 *
 * <p>The {@code Iterator} created by calling the {@code iterator} method
 * may throw a {@code ConcurrentModificationException} if the map is structurally
 * changed while an iterator is used to iterate over the elements. Only the
 * {@code remove} method that is provided by the iterator allows for removal of
 * elements during iteration. It is not possible to guarantee that this
 * mechanism works in all cases of unsynchronized concurrent modification. It
 * should only be used for debugging purposes.
 *
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 */

HashMap是Map的一種常用實現(xiàn)讹弯。HashMap中的元素排列無序橙凳,如果需要有序排列丘损,請用LinkedHashMap啤它。

    /**
     * Min capacity (other than zero) for a HashMap. Must be a power of two
     * greater than 1 (and less than 1 << 30).
     */
    private static final int MINIMUM_CAPACITY = 4;

JDK中HashMap的初始容量是16奕筐,而此處為4。

    /**
     * An empty table shared by all zero-capacity maps (typically from default
     * constructor). It is never written to, and replaced on first put. Its size
     * is set to half the minimum, so that the first resize will create a
     * minimum-sized table.
     */
    private static final Entry[] EMPTY_TABLE
            = new HashMapEntry[MINIMUM_CAPACITY >>> 1];

空HashMap持有的空表变骡,大小為2(擴容后變成4)离赫。

    /**
     * The default load factor. Note that this implementation ignores the
     * load factor, but cannot do away with it entirely because it's
     * mentioned in the API.
     *
     * <p>Note that this constant has no impact on the behavior of the program,
     * but it is emitted as part of the serialized form. The load factor of
     * .75 is hardwired into the program, which uses cheap shifts in place of
     * expensive division.
     */
    static final float DEFAULT_LOAD_FACTOR = .75F;

加載因子固定為0.75。當(dāng)實際大小超過當(dāng)前容量*加載因子時進(jìn)行擴容塌碌。實際上是由閾值threshold控制渊胸。

    /**
     * The hash table. If this hash map contains a mapping for null, it is
     * not represented this hash table.
     */
    transient HashMapEntry<K, V>[] table;

保存Entry的table數(shù)組。注意這里也用了transient 修飾符台妆,原理同ArrayList(見前一篇)翎猛。

    /**
     * The entry representing the null key, or null if there's no such mapping.
     */
    transient HashMapEntry<K, V> entryForNullKey;

保存key為空的Entry胖翰。

    /**
     * The table is rehashed when its size exceeds this threshold.
     * The value of this field is generally .75 * capacity, except when
     * the capacity is zero, as described in the EMPTY_TABLE declaration
     * above.
     */
    private transient int threshold;

閾值。當(dāng)實際大小超過閾值時重新進(jìn)行哈希切厘。

    /**
     * Constructs a new empty {@code HashMap} instance.
     */
    @SuppressWarnings("unchecked")
    public HashMap() {
        table = (HashMapEntry<K, V>[]) EMPTY_TABLE;
        threshold = -1; // Forces first put invocation to replace EMPTY_TABLE
    }

    /**
     * Constructs a new {@code HashMap} instance with the specified capacity.
     *
     * @param capacity
     *            the initial capacity of this hash map.
     * @throws IllegalArgumentException
     *                when the capacity is less than zero.
     */
    public HashMap(int capacity) {
        if (capacity < 0) {
            throw new IllegalArgumentException("Capacity: " + capacity);
        }

        if (capacity == 0) {
            @SuppressWarnings("unchecked")
            HashMapEntry<K, V>[] tab = (HashMapEntry<K, V>[]) EMPTY_TABLE;
            table = tab;
            threshold = -1; // Forces first put() to replace EMPTY_TABLE
            return;
        }

        if (capacity < MINIMUM_CAPACITY) {
            capacity = MINIMUM_CAPACITY;
        } else if (capacity > MAXIMUM_CAPACITY) {
            capacity = MAXIMUM_CAPACITY;
        } else {
            capacity = Collections.roundUpToPowerOfTwo(capacity);
        }
        makeTable(capacity);
    }

HashMap的幾個構(gòu)造函數(shù)萨咳。不指定容量的情況下table指向EMPTY_TABLE;指定容量的情況下容量將被調(diào)整為大于4的2的某次方值迂卢。

    static class HashMapEntry<K, V> implements Entry<K, V> {
        final K key;
        V value;
        final int hash;
        HashMapEntry<K, V> next;

        HashMapEntry(K key, V value, int hash, HashMapEntry<K, V> next) {
            this.key = key;
            this.value = value;
            this.hash = hash;
            this.next = next;
        }

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

        public final V setValue(V value) {
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        @Override public final boolean equals(Object o) {
            if (!(o instanceof Entry)) {
                return false;
            }
            Entry<?, ?> e = (Entry<?, ?>) o;
            return Objects.equal(e.getKey(), key)
                    && Objects.equal(e.getValue(), value);
        }

        @Override public final int hashCode() {
            return (key == null ? 0 : key.hashCode()) ^
                    (value == null ? 0 : value.hashCode());
        }

        @Override public final String toString() {
            return key + "=" + value;
        }
    }

Entry類某弦,HashMap內(nèi)部的數(shù)據(jù)結(jié)構(gòu)。table是HashMapEntry數(shù)組而克,同時HashMapEntry有一個HashMapEntry類型的next指針靶壮。當(dāng)數(shù)組哈希位置已經(jīng)存在元素時將新元素加入到該位置的鏈表末位,這也就是哈希沖突處理方法中的拉鏈法员萍。

    /**
     * Maps the specified key to the specified value.
     *
     * @param key
     *            the key.
     * @param value
     *            the value.
     * @return the value of any previous mapping with the specified key or
     *         {@code null} if there was no such mapping.
     */
    @Override public V put(K key, V value) {
        if (key == null) {
            return putValueForNullKey(value);
        }

        int hash = Collections.secondaryHash(key);
        HashMapEntry<K, V>[] tab = table;
        int index = hash & (tab.length - 1);
        for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) {
            if (e.hash == hash && key.equals(e.key)) {
                preModify(e);
                V oldValue = e.value;
                e.value = value;
                return oldValue;
            }
        }

        // No entry for (non-null) key is present; create one
        modCount++;
        if (size++ > threshold) {
            tab = doubleCapacity();
            index = hash & (tab.length - 1);
        }
        addNewEntry(key, value, hash, index);
        return null;
    }

    /**
     * Creates a new entry for the given key, value, hash, and index and
     * inserts it into the hash table. This method is called by put
     * (and indirectly, putAll), and overridden by LinkedHashMap. The hash
     * must incorporate the secondary hash function.
     */
    void addNewEntry(K key, V value, int hash, int index) {
        table[index] = new HashMapEntry<K, V>(key, value, hash, table[index]);
    }

增腾降。對key二次哈希,與運算(相當(dāng)于hash%length但是效率更高)得到index碎绎,然后遍歷index對應(yīng)的鏈表查找key相同的Entry螃壤,若有則替換之,若無則先判斷是否需要擴容筋帖,再添加新Entry奸晴,將新Entry作為鏈表頭并指向原來的鏈表頭。如上文所說日麸,這是拉鏈法的應(yīng)用寄啼。

    /**
     * Doubles the capacity of the hash table. Existing entries are placed in
     * the correct bucket on the enlarged table. If the current capacity is,
     * MAXIMUM_CAPACITY, this method is a no-op. Returns the table, which
     * will be new unless we were already at MAXIMUM_CAPACITY.
     */
    private HashMapEntry<K, V>[] doubleCapacity() {
        HashMapEntry<K, V>[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            return oldTable;
        }
        int newCapacity = oldCapacity * 2;
        HashMapEntry<K, V>[] newTable = makeTable(newCapacity);
        if (size == 0) {
            return newTable;
        }

        for (int j = 0; j < oldCapacity; j++) {
            /*
             * Rehash the bucket using the minimum number of field writes.
             * This is the most subtle and delicate code in the class.
             */
            HashMapEntry<K, V> e = oldTable[j];
            if (e == null) {
                continue;
            }
            int highBit = e.hash & oldCapacity;
            HashMapEntry<K, V> broken = null;
            newTable[j | highBit] = e;
            for (HashMapEntry<K, V> n = e.next; n != null; e = n, n = n.next) {
                int nextHighBit = n.hash & oldCapacity;
                if (nextHighBit != highBit) {
                    if (broken == null)
                        newTable[j | nextHighBit] = n;
                    else
                        broken.next = n;
                    broken = e;
                    highBit = nextHighBit;
                }
            }
            if (broken != null)
                broken.next = null;
        }
        return newTable;
    }

擴容。擴容大小是固定的2倍代箭。難點是擴容之后重新哈希的這段頗為風(fēng)騷的代碼墩划。倒是在行間注釋里特地寫一句“This is the most subtle and delicate code in the class”是幾個意思www。這里是以(hash & oldCapacity) | j求出index嗡综,該結(jié)果和hash & newCapacity - 1的運算結(jié)果相等乙帮,可以作出證明:
(hash & oldCapacity) | j
= (hash & oldCapacity) | (hash & (oldCapacity - 1))
= hash & (oldCapacity | (oldCapacity - 1))
因為容量capacity為2的某次冪,如4(0100)极景,8(1000)察净,形為除了第n位為1其他位為0;capacity - 1形為從第1位到第n - 1位為1其他位為0盼樟;則capacity | (capacity - 1)形為從第1位到第n位為1其他位為0塞绿,即capacity * 2 - 1也就是newCapacity - 1。
運算如此巧妙以至于讓人初見如墜五里云霧恤批。然而為什么要如此這番而不是直接使用hash & newCapacity - 1呢?就運算步驟來說反而是多了一步或運算裹赴。關(guān)于這個問題喜庞,我依舊不得其解诀浪。
將鏈表頭移動到新表后遍歷鏈表,判斷每個Entry是否需要移動延都,判斷的依據(jù)是高位是否相等雷猪,相等說明該Entry與上一Entry位于同一鏈表。
broken的作用是移動Entry之后將原鏈表上被移走的部分截掉晰房。

    /**
     * Removes the mapping with the specified key from this map.
     *
     * @param key
     *            the key of the mapping to remove.
     * @return the value of the removed mapping or {@code null} if no mapping
     *         for the specified key was found.
     */
    @Override public V remove(Object key) {
        if (key == null) {
            return removeNullKey();
        }
        int hash = Collections.secondaryHash(key);
        HashMapEntry<K, V>[] tab = table;
        int index = hash & (tab.length - 1);
        for (HashMapEntry<K, V> e = tab[index], prev = null;
                e != null; prev = e, e = e.next) {
            if (e.hash == hash && key.equals(e.key)) {
                if (prev == null) {
                    tab[index] = e.next;
                } else {
                    prev.next = e.next;
                }
                modCount++;
                size--;
                postRemove(e);
                return e.value;
            }
        }
        return null;
    }

刪求摇。原理和put類似。若刪除的Entry是鏈表頭則將下一Entry作為鏈表頭殊者,否則將上一Entry的next指向刪除Entry的next与境。

    /**
     * Returns the value of the mapping with the specified key.
     *
     * @param key
     *            the key.
     * @return the value of the mapping with the specified key, or {@code null}
     *         if no mapping for the specified key is found.
     */
    public V get(Object key) {
        if (key == null) {
            HashMapEntry<K, V> e = entryForNullKey;
            return e == null ? null : e.value;
        }

        int hash = Collections.secondaryHash(key);
        HashMapEntry<K, V>[] tab = table;
        for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];
                e != null; e = e.next) {
            K eKey = e.key;
            if (eKey == key || (e.hash == hash && key.equals(eKey))) {
                return e.value;
            }
        }
        return null;
    }

查。與上面類似的原理猖吴。

谷歌對Android環(huán)境下的HashMap進(jìn)行了一定的優(yōu)化摔刁,同時也推出了在一些場景下性能更好的替代品SparseArray和ArrayMap。另外若在多線程環(huán)境中海蔽,應(yīng)使用ConcurrentHashMap而不是HashMap共屈。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市党窜,隨后出現(xiàn)的幾起案子拗引,更是在濱河造成了極大的恐慌,老刑警劉巖幌衣,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件矾削,死亡現(xiàn)場離奇詭異,居然都是意外死亡泼掠,警方通過查閱死者的電腦和手機怔软,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來择镇,“玉大人挡逼,你說我怎么就攤上這事∧逋悖” “怎么了家坎?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長吝梅。 經(jīng)常有香客問我虱疏,道長,這世上最難降的妖魔是什么苏携? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任做瞪,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘装蓬。我一直安慰自己著拭,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布牍帚。 她就那樣靜靜地躺著儡遮,像睡著了一般。 火紅的嫁衣襯著肌膚如雪暗赶。 梳的紋絲不亂的頭發(fā)上鄙币,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天,我揣著相機與錄音蹂随,去河邊找鬼十嘿。 笑死,一個胖子當(dāng)著我的面吹牛糙及,可吹牛的內(nèi)容都是我干的详幽。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼浸锨,長吁一口氣:“原來是場噩夢啊……” “哼唇聘!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起柱搜,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤迟郎,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后聪蘸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體宪肖,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年健爬,在試婚紗的時候發(fā)現(xiàn)自己被綠了控乾。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡娜遵,死狀恐怖蜕衡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情设拟,我是刑警寧澤慨仿,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站纳胧,受9級特大地震影響镰吆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜跑慕,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一万皿、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦相寇、人聲如沸慰于。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至绵脯,卻和暖如春佳励,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蛆挫。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工赃承, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人悴侵。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓瞧剖,卻偏偏與公主長得像,于是被迫代替她去往敵國和親可免。 傳聞我的和親對象是個殘疾皇子抓于,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內(nèi)容