首頁 > Java > java教程 > 主體

深入理解java中HashMap的實作原理(圖)

黄舟
發布: 2017-03-28 10:32:59
原創
1658 人瀏覽過

這篇文章主要介紹了java 中HashMap實現原理深入理解的相關資料,需要的朋友可以參考下

1. HashMap的資料結構

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

      陣列

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

鍊錶

鍊錶儲存區間離散,佔用記憶體比較寬鬆,故空間複雜度很小,但時間複雜度很大,達O(N)。 鍊錶的特點是:尋址困難,插入和刪除容易。

哈希表

那我們能不能綜合兩者的特性,做出一種尋址容易,插入刪除也容易的資料結構?答案是肯定的,這就是我們要提起的哈希表。哈希表((Hash table)既滿足了資料的查找方便,同時不佔用太多的內容空間,使用也十分方便。

  哈希表有多種不同的實作方法,我接下來解釋的是最常用的方法- 拉鍊法,我們可以理解為「鍊錶的陣列」 ,如圖:

深入理解java中HashMap的實作原理(圖)

深入理解java中HashMap的實作原理(圖)

##  從上圖我們可以發現哈希表是由

數組+鍊錶組成的,一個長度為16的數組中,每個元素存儲的是一個鍊錶的頭結點。例如上述哈希表中,12%16=12,28%16=12,108%16=12,140%16=12。 ##  HashMap其實也是一個線性的數組實現的,所以可以理解為其存儲資料的容器就是一個線性數組 這裡。 HashMap有做一些處理。 ,從屬性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;
登入後複製

1)put

#疑問:如果兩個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的大致實現,我們應該已經清楚了。

// 存储时:
int hash = key.hashCode(); // 这个hashCode方法这里不详述,只要理解每个key的hash是一个固定的int值
int index = hash % Entry[].length;
Entry[index] = value;

// 取值时:
int hash = key.hashCode();
int index = hash % Entry[].length;
return Entry[index];
登入後複製
 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<K,V> e = table[i]; e != null; e = e.next) {

      Object k;

      //如果key在链表中已存在,则替换为新value

      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;

  }
登入後複製

  當然HashMap裡面也包含一些最佳化方面的實現,這裡也說一下。例如:Entry[]的長度一定後,隨著map裡面資料的越來越長,這樣同一個index的鏈就會很長,會不會影響效能? HashMap裡面設定一個因子,隨著map的size越來越大,Entry[]會以一定的規則加長長度。

2)get

 void addEntry(int hash, K key, V value, int bucketIndex) {

  Entry<K,V> e = table[bucketIndex];

  table[bucketIndex] = new Entry<K,V>(hash, key, value, e);//参数e, 是Entry.next

  //如果size超过threshold,则扩充table大小。再散列

  if (size++ >= threshold)

      resize(2 * table.length);

}
登入後複製

 3)null key的存取

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

public V get(Object key) {

    if (key == null)

      return getForNullKey();

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

    //先定位到数组元素,再遍历该元素处的链表

    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.equals(k)))

        return e.value;

    }

    return null;

}
登入後複製
 4)決定陣列index:hashcode % table.length取模

HashMap存取時,都需要計算目前key應該對應Entry[]陣列哪個元素,即計算數組下標;演算法如下:

 private V putForNullKey(V value) {

    for (Entry<K,V> e = table[0]; e != null; e = e.next) {

      if (e.key == null) {

        V oldValue = e.value;

        e.value = value;

        e.recordAccess(this);

        return oldValue;

      }

    }

    modCount++;

    addEntry(0, null, value, 0);

    return null;

  }

 


  private V getForNullKey() {

    for (Entry<K,V> e = table[0]; e != null; e = e.next) {

      if (e.key == null)

        return e.value;

    }

    return null;

  }
登入後複製

以位元取併,作用上相當於取模mod或取餘%。

這表示陣列下標相同,並不表示hashCode相同。

5)table初始大小

 public HashMap(int initialCapacity, float loadFactor) {

    ..... 


    // Find a power of 2 >= initialCapacity 

    int capacity = 1;

    while (capacity < initialCapacity)

      capacity <<= 1;


    this.loadFactor = loadFactor;

    threshold = (int)(capacity * loadFactor);

    table = new Entry[capacity];

    init();

  }
登入後複製

注意table初始大小并不是构造函数中的initialCapacity!!

而是 >= initialCapacity的2的n次幂!!!!

————为什么这么设计呢?——

3. 解决hash冲突的办法开放定址法(线性探测再散列,二次探测再散列,伪随机探测再散列) 再哈希法 链地址法 建立一个公共溢出区

Java中hashmap的解决办法就是采用的链地址法。

4. 再散列rehash过程

当哈希表的容量超过默认容量时,必须调整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 < src.length; j++) {

      Entry<K,V> e = src[j];

      if (e != null) {

        src[j] = null;

        do {

          Entry<K,V> next = e.next;

          //重新计算index

          int i = indexFor(e.hash, newCapacity);

          e.next = newTable[i];

          newTable[i] = e;

          e = next;

        } while (e != null);

      }

    }

  }
登入後複製

以上是深入理解java中HashMap的實作原理(圖)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!