HashMap(jdk1.7)源碼筆記

感覺大部分是鏈表操作

  • 插入一個k,v ,判斷是否擴(kuò)容,求index,插入到數(shù)組的第index鏈表中
  • 刪除一個k,v, 求index,在鏈表中查找,刪除鏈表節(jié)點(diǎn)
  • 每次更改會有一個modcount記錄,iterator的每個方法調(diào)用會判斷這個值變沒變,變了就拋出ConcurrentModificationException
  • 后面有總結(jié)
public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        //MAXIMUM_CAPACITY 最大容量
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
}

put

/**
     * An empty table instance to share when the table is not inflated.
     */
    static final Entry<?,?>[] EMPTY_TABLE = {};

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

/**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
      //列表沒有容量的話,調(diào)用inflatTable()
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
      
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            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++;
        addEntry(hash, key, value, i);
        return null;
    }

    // 容量是2的冪,聲明一個新的Entry數(shù)組,容量為capacity
   private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize);

        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    }


    private V putForNullKey(V value) {
      // null key的話一般保存在table的第0個鏈表中,依次查找,如果原來不存在k為null的節(jié)點(diǎn)
      // 則調(diào)用addEntry
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                //recoreAccess()空方法,可能是為了子類繼承
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }

/**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.(按需擴(kuò)容)
     *
     * Subclass overrides this to alter the behavior of put method.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
      //當(dāng)前size超出均衡因子 而且鏈表數(shù)組中的節(jié)點(diǎn)已經(jīng)初始化,則擴(kuò)容
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
          //得到擴(kuò)容后的index
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
    }


/**
     * 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.
     *
     * @param newCapacity the new capacity, MUST be a power of two;
     *        must be greater than current capacity unless current
     *        capacity is MAXIMUM_CAPACITY (in which case value
     *        is irrelevant).
     */
    void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
      //如果已經(jīng)是最大容量了,那么只更改threshold,避免后面繼續(xù)調(diào)用擴(kuò)容
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
      //將舊的table復(fù)制到新的table中
        transfer(newTable, initHashSeedAsNeeded(newCapacity));
        table = newTable;
      //更改負(fù)載因子
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
          //每次把鏈表節(jié)點(diǎn)插到新鏈表的頭部
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
              //根據(jù)hash值計算新的位置
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

//01111111  length - 1
//10101001  hash 
//快速求余數(shù)
static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }



/**
     * 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.
     */
//創(chuàng)建一個新的Entry,插入鏈表頭部
    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

get

/**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

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

    //在index為0的鏈表中查找k為null的Entry
    private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }
    
    /**
     * Returns the entry associated with the specified key in the
     * HashMap.  Returns null if the HashMap contains no mapping
     * for the key.
     */
    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        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;
    }

remove

public V remove(Object key) {
    Entry<K,V> e = removeEntryForKey(key);
    return (e == null ? null : e.value);
}

/**
     * Removes and returns the entry associated with the specified key
     * in the HashMap.  Returns null if the HashMap contains no mapping
     * for this key.
     */
    final Entry<K,V> removeEntryForKey(Object key) {
        if (size == 0) {
            return null;
        }
        int hash = (key == null) ? 0 : hash(key);
        int i = indexFor(hash, table.length);
        Entry<K,V> prev = table[i];
        Entry<K,V> e = prev;

        while (e != null) {
            Entry<K,V> next = e.next;
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                modCount++;
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }

        return e;
    }

Iterator

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() {
          //記錄modeCOunt
            expectedModCount = modCount;
            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() {
          //不相等就拋出ConcurrentModificationException
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
            current = e;
            return e;
        }

        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;
        }
    }

    private final class ValueIterator extends HashIterator<V> {
        public V next() {
            return nextEntry().value;
        }
    }

    private final class KeyIterator extends HashIterator<K> {
        public K next() {
            return nextEntry().getKey();
        }
    }

    private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
        public Map.Entry<K,V> next() {
            return nextEntry();
        }
    }

總結(jié)

參考這篇文章

為什么哈希表的容量一定要是2的整數(shù)次冪貌夕。

  • 首先崇裁,length為2的整數(shù)次冪的話袁滥,h&(length-1)就相當(dāng)于對length取模,這樣便保證了散列的均勻膏潮,同時也提升了效率踱讨;
  • 其次悴侵,length為2的整數(shù)次冪的話箱叁,為偶數(shù),這樣length-1為奇數(shù)积蔚,奇數(shù)的最后一位是1意鲸,這樣便保證了h&(length-1)的最后一位可能為0,也可能為1(這取決于h的值)库倘,即與后的結(jié)果可能為偶數(shù)临扮,也可能為奇數(shù),這樣便可以保證散列的均勻性教翩,而如果length為奇數(shù)的話杆勇,很明顯length-1為偶數(shù),它的最后一位是0饱亿,這樣h&(length-1)的最后一位肯定為0蚜退,即只能為偶數(shù),這樣任何hash值都只會被散列到數(shù)組的偶數(shù)下標(biāo)位置上彪笼,這便浪費(fèi)了近一半的空間钻注,
  • 因此,length取2的整數(shù)次冪配猫,是為了使不同hash值發(fā)生碰撞的概率較小幅恋,這樣就能使元素在哈希表中均勻地散列。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末泵肄,一起剝皮案震驚了整個濱河市捆交,隨后出現(xiàn)的幾起案子淑翼,更是在濱河造成了極大的恐慌,老刑警劉巖品追,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件玄括,死亡現(xiàn)場離奇詭異,居然都是意外死亡肉瓦,警方通過查閱死者的電腦和手機(jī)遭京,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泞莉,“玉大人哪雕,你說我怎么就攤上這事〗洳疲” “怎么了热监?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵捺弦,是天一觀的道長饮寞。 經(jīng)常有香客問我,道長列吼,這世上最難降的妖魔是什么幽崩? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮寞钥,結(jié)果婚禮上慌申,老公的妹妹穿的比我還像新娘。我一直安慰自己理郑,他們只是感情好蹄溉,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著您炉,像睡著了一般柒爵。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上赚爵,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天棉胀,我揣著相機(jī)與錄音,去河邊找鬼冀膝。 笑死唁奢,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的窝剖。 我是一名探鬼主播麻掸,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼赐纱!你這毒婦竟也來了脊奋?” 一聲冷哼從身側(cè)響起采郎,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎狂魔,沒想到半個月后蒜埋,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡最楷,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年整份,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片籽孙。...
    茶點(diǎn)故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡烈评,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出犯建,到底是詐尸還是另有隱情讲冠,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布适瓦,位于F島的核電站竿开,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏玻熙。R本人自食惡果不足惜否彩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望嗦随。 院中可真熱鬧列荔,春花似錦、人聲如沸枚尼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽署恍。三九已至崎溃,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間锭汛,已是汗流浹背笨奠。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留唤殴,地道東北人般婆。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像朵逝,于是被迫代替她去往敵國和親蔚袍。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評論 2 354

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

  • 1.HashMap是一個數(shù)組+鏈表/紅黑樹的結(jié)構(gòu),數(shù)組的下標(biāo)在HashMap中稱為Bucket值啤咽,每個數(shù)組項對應(yīng)的...
    誰在烽煙彼岸閱讀 1,025評論 2 2
  • 一宇整、基本數(shù)據(jù)類型 注釋 單行注釋:// 區(qū)域注釋:/* */ 文檔注釋:/** */ 數(shù)值 對于byte類型而言...
    龍貓小爺閱讀 4,261評論 0 16
  • 槍炮 病毒 鋼鐵 印加帝國覆滅 由于西方國家?guī)淼奶旎?/div>
    宮曉杰閱讀 119評論 0 0
  • 抬頭仰望天空藍(lán)瓶佳,天上白云朵朵綻。若問云兒從那來鳞青,萬里晴空云渺渺霸饲。仰望天空白云飄,白云蒼狗世變遷臂拓。若問云兒那里去厚脉,天...
    甘朝武閱讀 601評論 0 0
  • 有兩個賣藝人A和B傻工,手提琴拉得非常好,他們都在同一條街上賣藝孵滞,收入可觀中捆。 有一天,A向B告別剃斧,他積攢了一筆...
    追夢進(jìn)行時2016閱讀 451評論 0 0