天天看點

HashMap原了解析

資料結構中有數組和連結清單來實作對資料的存儲,但這兩者基本上是兩個極端。

數組存儲區間是連續的,占用記憶體嚴重,故空間複雜的很大。但數組的二分查找時間複雜度小,為o(1);數組的特點是:尋址容易,插入和删除困難;

連結清單存儲區間離散,占用記憶體比較寬松,故空間複雜度很小,但時間複雜度很大,達o(n)。連結清單的特點是:尋址困難,插入和删除容易。

那麼我們能不能綜合兩者的特性,做出一種尋址容易,插入删除也容易的資料結構?答案是肯定的,這就是我們要提起的哈希表。哈希表((hash

table)既滿足了資料的查找友善,同時不占用太多的内容空間,使用也十分友善。

  哈希表有多種不同的實作方法,我接下來解釋的是最常用的一種方法—— 拉鍊法,我們可以了解為“連結清單的數組” ,如圖:

HashMap原了解析
HashMap原了解析

  從上圖我們可以發現哈希表是由數組+連結清單組成的,一個長度為16的數組中,每個元素存儲的是一個連結清單的頭結點。那麼這些元素是按照什麼樣的規則存儲到數組中呢。一般情況是通過hash(key)%len獲得,也就是元素的key的哈希值對數組長度取模得到。比如上述哈希表中,12%16=12,28%16=12,108%16=12,140%16=12。是以12、28、108以及140都存儲在數組下标為12的位置。

  hashmap其實也是一個線性的數組實作的,是以可以了解為其存儲資料的容器就是一個線性數組。這可能讓我們很不解,一個線性的數組怎麼實作按鍵值對來存取資料呢?這裡hashmap有做一些處理。

  首先hashmap裡面實作一個靜态内部類entry,其重要的屬性有 key , value, next,從屬性key,value我們就能很明顯的看出來entry就是hashmap鍵值對實作的一個基礎bean,我們上面說到hashmap的基礎就是一個線性數組,這個數組就是entry[],map裡面的内容都儲存在entry[]裡面。

    /**

     * the table, resized as necessary. length must always be a power of two.

     */

    transient entry[] table;

     既然是線性數組,為什麼能随機存取?這裡hashmap用了一個小算法,大緻是這樣實作:

<code></code>

// 存儲時:

int hash = key.hashcode(); // 這個hashcode方法這裡不詳述,隻要了解每個key的hash是一個固定的int值

int index = hash % entry[].length;

entry[index] = value;

// 取值時:

int hash = key.hashcode();

return entry[index];

疑問:如果兩個key通過hash%entry[].length得到的index相同,會不會有覆寫的危險?

  這裡hashmap裡面用到鍊式資料結構的一個概念。上面我們提到過entry類裡面有一個next屬性,作用是指向下一個entry。打個比方, 第一個鍵值對a進來,通過計算其key的hash得到的index=0,記做:entry[0] = a。一會後又進來一個鍵值對b,通過計算其index也等于0,現在怎麼辦?hashmap會這樣做:b.next = a,entry[0] = b,如果又進來c,index也等于0,那麼c.next = b,entry[0] = c;這樣我們發現index=0的地方其實存取了a,b,c三個鍵值對,他們通過next這個屬性連結在一起。是以疑問不用擔心。也就是說數組中存儲的是最後插入的元素。到這裡為止,hashmap的大緻實作,我們應該已經清楚了。

 public v put(k key, v value) {

        if (key == null)

            return putfornullkey(value); //null總是放在數組的第一個連結清單中

        int hash = hash(key.hashcode());

        int i = indexfor(hash, table.length);

        //周遊連結清單

        for (entry&lt;k,v&gt; e = table[i]; e != null; e = e.next) {

            object k;

            //如果key在連結清單中已存在,則替換為新value

            if (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k))) {

                v oldvalue = e.value;

                e.value = value;

                e.recordaccess(this);

                return oldvalue;

            }

        }

        modcount++;

       //将entry添加到連結清單中去

        addentry(hash, key, value, i);

        return null;

    }

void addentry(int hash, k key, v value, int bucketindex) {

    entry&lt;k,v&gt; e = table[bucketindex];

    table[bucketindex] = new entry&lt;k,v&gt;(hash, key, value, e); //參數e,

是entry.next

    //如果size超過threshold,則擴充table大小。再散列

    if (size++ &gt;= threshold)

            resize(2 * table.length);

}

  當然hashmap裡面也包含一些優化方面的實作,這裡也說一下。比如:entry[]的長度一定後,随着map裡面資料的越來越長,這樣同一個index的鍊就會很長,會不會影響性能?hashmap裡面設定一個因子,随着map的size越來越大,entry[]會以一定的規則加長長度。

static final entry&lt;?,?&gt;[] empty_table = {};

 public v get(object key) {

            return getfornullkey();

        //先定位到數組元素,再周遊該元素處的連結清單

        for (entry&lt;k,v&gt; e = table[indexfor(hash, table.length)];

             e != null;

             e = e.next) {

            if (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k)))

                return e.value;

null key總是存放在entry[]數組的第一個元素。

   private v putfornullkey(v value) {

        for (entry&lt;k,v&gt; e = table[0]; e != null; e = e.next) {

            if (e.key == null) {

        addentry(0, null, value, 0);

    private v getfornullkey() {

            if (e.key == null)

hashmap存取時,都需要計算目前key應該對應entry[]數組哪個元素,即計算數組下标;算法如下:

   /**

     * returns index for hash code h.

    static int indexfor(int h, int length) {

        return h &amp; (length-1);

按位取并,作用上相當于取模mod或者取餘%。

這意味着數組下标相同,并不表示hashcode相同。

  public hashmap(int initialcapacity, float loadfactor) {

        .....

        // find a power of 2 &gt;= initialcapacity

        int capacity = 1;

        while (capacity &lt; initialcapacity)

            capacity &lt;&lt;= 1;

        this.loadfactor = loadfactor;

        threshold = (int)(capacity * loadfactor);

        table = new entry[capacity];

        init();

注意table初始大小并不是構造函數中的initialcapacity!!

而是 &gt;= initialcapacity的2的n次幂!!!!

當哈希表的容量超過預設容量時,必須調整table的大小。當容量已經達到最大可能值時,那麼該方法就将容量調整到integer.max_value傳回,這時,需要建立一張新表,将原表的映射到新表中。

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

        if (oldcapacity == maximum_capacity) {

            threshold = integer.max_value;

            return;

        entry[] newtable = new entry[newcapacity];

        transfer(newtable);

        table = newtable;

        threshold = (int)(newcapacity * loadfactor);

     * transfers all entries from current table to newtable.

    void transfer(entry[] newtable) {

        entry[] src = table;

        int newcapacity = newtable.length;

        for (int j = 0; j &lt; src.length; j++) {

            entry&lt;k,v&gt; e = src[j];

            if (e != null) {

                src[j] = null;

                do {

                    entry&lt;k,v&gt; next = e.next;

                    //重新計算index

                    int i = indexfor(e.hash, newcapacity);

                    e.next = newtable[i];

                    newtable[i] = e;

                    e = next;

                } while (e != null);

繼續閱讀