亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

java 中HashMap實(shí)現(xiàn)原理深入理解

 更新時(shí)間:2017年03月27日 11:33:53   作者:AlphaWang  
這篇文章主要介紹了java 中HashMap實(shí)現(xiàn)原理深入理解的相關(guān)資料,需要的朋友可以參考下

1. HashMap的數(shù)據(jù)結(jié)構(gòu)

數(shù)據(jù)結(jié)構(gòu)中有數(shù)組和鏈表來(lái)實(shí)現(xiàn)對(duì)數(shù)據(jù)的存儲(chǔ),但這兩者基本上是兩個(gè)極端。

      數(shù)組

數(shù)組存儲(chǔ)區(qū)間是連續(xù)的,占用內(nèi)存嚴(yán)重,故空間復(fù)雜的很大。但數(shù)組的二分查找時(shí)間復(fù)雜度小,為O(1);數(shù)組的特點(diǎn)是:尋址容易,插入和刪除困難;

鏈表

鏈表存儲(chǔ)區(qū)間離散,占用內(nèi)存比較寬松,故空間復(fù)雜度很小,但時(shí)間復(fù)雜度很大,達(dá)O(N)。鏈表的特點(diǎn)是:尋址困難,插入和刪除容易。

哈希表

那么我們能不能綜合兩者的特性,做出一種尋址容易,插入刪除也容易的數(shù)據(jù)結(jié)構(gòu)?答案是肯定的,這就是我們要提起的哈希表。哈希表((Hash table)既滿足了數(shù)據(jù)的查找方便,同時(shí)不占用太多的內(nèi)容空間,使用也十分方便。

  哈希表有多種不同的實(shí)現(xiàn)方法,我接下來(lái)解釋的是最常用的一種方法—— 拉鏈法,我們可以理解為“鏈表的數(shù)組” ,如圖:



  從上圖我們可以發(fā)現(xiàn)哈希表是由數(shù)組+鏈表組成的,一個(gè)長(zhǎng)度為16的數(shù)組中,每個(gè)元素存儲(chǔ)的是一個(gè)鏈表的頭結(jié)點(diǎn)。那么這些元素是按照什么樣的規(guī)則存儲(chǔ)到數(shù)組中呢。一般情況是通過(guò)hash(key)%len獲得,也就是元素的key的哈希值對(duì)數(shù)組長(zhǎng)度取模得到。比如上述哈希表中,12%16=12,28%16=12,108%16=12,140%16=12。所以12、28、108以及140都存儲(chǔ)在數(shù)組下標(biāo)為12的位置。

  HashMap其實(shí)也是一個(gè)線性的數(shù)組實(shí)現(xiàn)的,所以可以理解為其存儲(chǔ)數(shù)據(jù)的容器就是一個(gè)線性數(shù)組。這可能讓我們很不解,一個(gè)線性的數(shù)組怎么實(shí)現(xiàn)按鍵值對(duì)來(lái)存取數(shù)據(jù)呢?這里HashMap有做一些處理。

  首先HashMap里面實(shí)現(xiàn)一個(gè)靜態(tài)內(nèi)部類(lèi)Entry,其重要的屬性有key , value, next,從屬性key,value我們就能很明顯的看出來(lái)Entry就是HashMap鍵值對(duì)實(shí)現(xiàn)的一個(gè)基礎(chǔ)bean,我們上面說(shuō)到HashMap的基礎(chǔ)就是一個(gè)線性數(shù)組,這個(gè)數(shù)組就是Entry[],Map里面的內(nèi)容都保存在Entry[]里面。

 /**

   * The table, resized as necessary. Length MUST Always be a power of two.

   */
    transient Entry[] table;

2. HashMap的存取實(shí)現(xiàn)

     既然是線性數(shù)組,為什么能隨機(jī)存???這里HashMap用了一個(gè)小算法,大致是這樣實(shí)現(xiàn):

// 存儲(chǔ)時(shí):
int hash = key.hashCode(); // 這個(gè)hashCode方法這里不詳述,只要理解每個(gè)key的hash是一個(gè)固定的int值
int index = hash % Entry[].length;
Entry[index] = value;

// 取值時(shí):
int hash = key.hashCode();
int index = hash % Entry[].length;
return Entry[index];

1)put

疑問(wèn):如果兩個(gè)key通過(guò)hash%Entry[].length得到的index相同,會(huì)不會(huì)有覆蓋的危險(xiǎn)?

  這里HashMap里面用到鏈?zhǔn)綌?shù)據(jù)結(jié)構(gòu)的一個(gè)概念。上面我們提到過(guò)Entry類(lèi)里面有一個(gè)next屬性,作用是指向下一個(gè)Entry。打個(gè)比方, 第一個(gè)鍵值對(duì)A進(jìn)來(lái),通過(guò)計(jì)算其key的hash得到的index=0,記做:Entry[0] = A。一會(huì)后又進(jìn)來(lái)一個(gè)鍵值對(duì)B,通過(guò)計(jì)算其index也等于0,現(xiàn)在怎么辦?HashMap會(huì)這樣做:B.next = A,Entry[0] = B,如果又進(jìn)來(lái)C,index也等于0,那么C.next = B,Entry[0] = C;這樣我們發(fā)現(xiàn)index=0的地方其實(shí)存取了A,B,C三個(gè)鍵值對(duì),他們通過(guò)next這個(gè)屬性鏈接在一起。所以疑問(wèn)不用擔(dān)心。也就是說(shuō)數(shù)組中存儲(chǔ)的是最后插入的元素。到這里為止,HashMap的大致實(shí)現(xiàn),我們應(yīng)該已經(jīng)清楚了。

 public V put(K key, V value) {

    if (key == null)

      return putForNullKey(value); //null總是放在數(shù)組的第一個(gè)鏈表中

    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;

  }

 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);//參數(shù)e, 是Entry.next

  //如果size超過(guò)threshold,則擴(kuò)充table大小。再散列

  if (size++ >= threshold)

      resize(2 * table.length);

}

  當(dāng)然HashMap里面也包含一些優(yōu)化方面的實(shí)現(xiàn),這里也說(shuō)一下。比如:Entry[]的長(zhǎng)度一定后,隨著map里面數(shù)據(jù)的越來(lái)越長(zhǎng),這樣同一個(gè)index的鏈就會(huì)很長(zhǎng),會(huì)不會(huì)影響性能?HashMap里面設(shè)置一個(gè)因子,隨著map的size越來(lái)越大,Entry[]會(huì)以一定的規(guī)則加長(zhǎng)長(zhǎng)度。

2)get

public V get(Object key) {

    if (key == null)

      return getForNullKey();

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

    //先定位到數(shù)組元素,再遍歷該元素處的鏈表

    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;

}

 3)null key的存取

null key總是存放在Entry[]數(shù)組的第一個(gè)元素。

 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;

  } 

 4)確定數(shù)組index:hashcode % table.length取模

HashMap存取時(shí),都需要計(jì)算當(dāng)前key應(yīng)該對(duì)應(yīng)Entry[]數(shù)組哪個(gè)元素,即計(jì)算數(shù)組下標(biāo);算法如下:

 /**

   * Returns index for hash code h.

   */

  static int indexFor(int h, int length) {

    return h & (length-1);

  }

按位取并,作用上相當(dāng)于取模mod或者取余%。

這意味著數(shù)組下標(biāo)相同,并不表示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初始大小并不是構(gòu)造函數(shù)中的initialCapacity?。?/strong>

而是 >= initialCapacity的2的n次冪!?。?!

————為什么這么設(shè)計(jì)呢?——

3. 解決hash沖突的辦法開(kāi)放定址法(線性探測(cè)再散列,二次探測(cè)再散列,偽隨機(jī)探測(cè)再散列) 再哈希法 鏈地址法 建立一個(gè)公共溢出區(qū)

Java中hashmap的解決辦法就是采用的鏈地址法。

4. 再散列rehash過(guò)程

當(dāng)哈希表的容量超過(guò)默認(rèn)容量時(shí),必須調(diào)整table的大小。當(dāng)容量已經(jīng)達(dá)到最大可能值時(shí),那么該方法就將容量調(diào)整到Integer.MAX_VALUE返回,這時(shí),需要?jiǎng)?chuàng)建一張新表,將原表的映射到新表中。

  /**

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

          //重新計(jì)算index

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

          e.next = newTable[i];

          newTable[i] = e;

          e = next;

        } while (e != null);

      }

    }

  }

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

  • Java的引用類(lèi)型常用的四種方法

    Java的引用類(lèi)型常用的四種方法

    這篇文章主要介紹了Java的引用類(lèi)型常用的幾種方法,Java為引用類(lèi)型專(zhuān)門(mén)定義了一個(gè)類(lèi)Reference,它是引用對(duì)象的抽象基類(lèi),相關(guān)內(nèi)容需要的小伙伴可以參考一下
    2022-06-06
  • 如何用注解的方式實(shí)現(xiàn)Mybatis插入數(shù)據(jù)時(shí)返回自增的主鍵Id

    如何用注解的方式實(shí)現(xiàn)Mybatis插入數(shù)據(jù)時(shí)返回自增的主鍵Id

    這篇文章主要介紹了如何用注解的方式實(shí)現(xiàn)Mybatis插入數(shù)據(jù)時(shí)返回自增的主鍵Id,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • 閑言碎語(yǔ)-逐步了解Spring

    閑言碎語(yǔ)-逐步了解Spring

    這篇文章主要介紹了閑言碎語(yǔ)-逐步了解Spring,涉及Spring的誕生,簡(jiǎn)介,作用等相關(guān)內(nèi)容,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11
  • SpringCloud Eureka服務(wù)發(fā)現(xiàn)實(shí)現(xiàn)過(guò)程

    SpringCloud Eureka服務(wù)發(fā)現(xiàn)實(shí)現(xiàn)過(guò)程

    這篇文章主要介紹了SpringCloud Eureka服務(wù)發(fā)現(xiàn)實(shí)現(xiàn)過(guò)程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • 詳解Spring bean的注解注入之@Autowired的原理及使用

    詳解Spring bean的注解注入之@Autowired的原理及使用

    之前講過(guò)bean注入是什么,也使用了xml的配置文件進(jìn)行bean注入,這也是Spring的最原始的注入方式(xml注入).本文主要講解的注解有以下幾個(gè):@Autowired、 @Service、@Repository、@Controller 、@Component、@Bean、@Configuration、@Resource ,需要的朋友可以參考下
    2021-06-06
  • java的equals和==的比較示例

    java的equals和==的比較示例

    這篇文章主要介紹了java的equals和==的比較示例,需要的朋友可以參考下
    2014-04-04
  • java如何實(shí)現(xiàn)自動(dòng)生成數(shù)據(jù)庫(kù)設(shè)計(jì)文檔

    java如何實(shí)現(xiàn)自動(dòng)生成數(shù)據(jù)庫(kù)設(shè)計(jì)文檔

    以前我們還需要手寫(xiě)數(shù)據(jù)庫(kù)設(shè)計(jì)文檔、現(xiàn)在可以通過(guò)引入screw核心包來(lái)實(shí)現(xiàn)Java?數(shù)據(jù)庫(kù)文檔一鍵生成。本文將具體介紹一下如何通過(guò)java自動(dòng)生成數(shù)據(jù)庫(kù)設(shè)計(jì)文檔,需要的朋友可以參考下
    2021-11-11
  • 關(guān)于RedisTemplate之opsForValue的使用說(shuō)明

    關(guān)于RedisTemplate之opsForValue的使用說(shuō)明

    這篇文章主要介紹了關(guān)于RedisTemplate之opsForValue的使用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • SpringBoot日程管理Quartz與定時(shí)任務(wù)Task實(shí)現(xiàn)詳解

    SpringBoot日程管理Quartz與定時(shí)任務(wù)Task實(shí)現(xiàn)詳解

    定時(shí)任務(wù)是企業(yè)級(jí)開(kāi)發(fā)中必不可少的組成部分,諸如長(zhǎng)周期業(yè)務(wù)數(shù)據(jù)的計(jì)算,例如年度報(bào)表,諸如系統(tǒng)臟數(shù)據(jù)的處理,再比如系統(tǒng)性能監(jiān)控報(bào)告,還有搶購(gòu)類(lèi)活動(dòng)的商品上架,這些都離不開(kāi)定時(shí)任務(wù)。本節(jié)將介紹兩種不同的定時(shí)任務(wù)技術(shù)
    2022-09-09
  • SpringMVC Cron定時(shí)器Demo常見(jiàn)問(wèn)題解決方案

    SpringMVC Cron定時(shí)器Demo常見(jiàn)問(wèn)題解決方案

    這篇文章主要介紹了SpringMVC Cron定時(shí)器Demo常見(jiàn)問(wèn)題解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11

最新評(píng)論