從頭認識java-15.7 Map(2)-介紹HashMap的工作原理-put方法

來源:互聯網
上載者:User

從頭認識java-15.7 Map(2)-介紹HashMap的工作原理-put方法

這一章節我們來介紹HashMap的工作原理。

1.HashMap的工作原理圖

引用自:http://www.admin10000.com/document/3322.html

2.HashMap初始化的時候我們可以這樣理解:一個數組,每一個位置儲存的是一個鏈表,鏈表裡面的每一個元素才是我們記錄的元素

 

3.下面我們來看put的源碼:

 

public V put(K key, V value) {        if (key == null)            return putForNullKey(value);        int hash = hash(key.hashCode());        int i = indexFor(hash, table.length);        for (Entry 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;    }

解釋:

 

a.當key為空白的時候,通過putForNullKey方法,把元素放到最開始的位置。注意:HashMap是允許Key為空白的。下面的代碼就是證明:

 

package com.ray.ch15;import java.util.HashMap;public class Test {public static void main(String[] args) {HashMap map = new HashMap();map.put(null, "1");}}

 

b.當key不為空白的時候,需要計算key的hashcode,因為hashCode()方法是繼承Object,因此每一個key都有這樣的方法。當然,我們也可以重寫hashCode(),但是這裡將出現一系列的問題,我們後面的章節再展開。

注意:其中有一個hash()方法,就是把Key的hashCode再一次hash,這樣做主要是為了使這個hash碼更加的平均分布,下面是hash的源碼:

 

static int hash(int h) {        // This function ensures that hashCodes that differ only by        // constant multiples at each bit position have a bounded        // number of collisions (approximately 8 at default load factor).        h ^= (h >>> 20) ^ (h >>> 12);        return h ^ (h >>> 7) ^ (h >>> 4);    }

然後我們再通過indexFor計算出這一系列元素放在大table的什麼位置。

 

 

d.當計算完鏈表在table上面的位置,我們就需要遍曆上面的元素,因此出現了for迴圈。

 

擴充(1):這裡需要突出一下上面所說的table,table的源碼:

 

 /**     * The table, resized as necessary. Length MUST Always be a power of two.     */    transient Entry[] table;

它是一個Entry組成的數組,這個Entry就是我們放到裡面的元素。

 

這個table,就是我們的左邊的Y軸上面的1,2,3,4.....它每一個位置上都是記錄一個Entry的鏈表。

從注釋可以看到,這個table是可變的,當Map的容量超過某一個界限,他就會觸發resize方法,從新建立一個table,然後把就的資料copy一份到新的裡面去。下面是resize的源碼:

 

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];        transfer(newTable);        table = newTable;        threshold = (int)(newCapacity * loadFactor);    }

擴充(2):講到table,我們必須將另一額重要參數裝載因子(DEFAULT_LOAD_FACTOR)。下面是裝載因子初始化的值,0.75,代表當Map的容量達到0.75的時候,將觸發resize方法,重新擴充Map的大小。這個因子的數值決定了一大部分Map 的效能,後面的章節將會說明。
/**     * The load factor used when none specified in constructor.     */    static final float DEFAULT_LOAD_FACTOR = 0.75f;

4.綜上所述,Map的put 的流程是:

(1)檢查key是否為空白

(2)計算key的hashcode和在table裡面的index(位置)

(3)找到table上面的元素

(4)遍曆鏈表,如果沒有就put進去,有就更新

總結:這一章節我們主要通過put方法來介紹HashMap的工作原理。

這一章節就到這裡,謝謝。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.