日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
簡單講解一下HashMap底層實(shí)現(xiàn)原理

HashMap是Map族中最為常用的一種,也是 Java Collection Framework 的重要成員,本篇文章重點(diǎn)為大家講解一下HashMap底層實(shí)現(xiàn)原理。

創(chuàng)新互聯(lián)的客戶來自各行各業(yè),為了共同目標(biāo),我們在工作上密切配合,從創(chuàng)業(yè)型小企業(yè)到企事業(yè)單位,感謝他們對我們的要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會用頭腦與智慧不斷的給客戶帶來驚喜。專業(yè)領(lǐng)域包括做網(wǎng)站、網(wǎng)站設(shè)計(jì)、電商網(wǎng)站開發(fā)、微信營銷、系統(tǒng)平臺開發(fā)。

1. 特性

我們可以用任何類作為HashMap的key,但是對于這些類應(yīng)該有什么限制條件呢?且看下面的代碼:

public class Person {
   private String name;

   public Person(String name) {
       this.name = name;
   }
}

Map testMap = new HashMap();
testMap.put(new Person("hello"), "world");
testMap.get(new Person("hello")); // ---> null

本是想取出具有相等字段值Person類的value,結(jié)果卻是null。對HashMap稍有了解的人看出來——Person類并沒有override hashcode方法,導(dǎo)致其繼承的是Object的hashcode(返回是其內(nèi)存地址),兩次new出來的Person對象并不equals——這也是為什么在工程項(xiàng)目中常用不變類(如String、Integer等)做為HashMap的key的原因。那么,HashMap是如何利用hashcode給key做索引的呢?

2. 原理

首先,我們來看《Thinking in Java》中一個(gè)簡單HashMap的實(shí)現(xiàn)方案:

//: containers/SimpleHashMap.java
// A demonstration hashed Map.
import java.util.*;
import net.mindview.util.*;

public class SimpleHashMap extends AbstractMap {
 // Choose a prime number for the hash table size, to achieve a uniform distribution:
 static final int SIZE = 997;
 // You can't have a physical array of generics, but you can upcast to one:  @SuppressWarnings("unchecked")  LinkedList>[] buckets =    new LinkedList[SIZE];  public V put(K key, V value) {    V oldValue = null;    int index = Math.abs(key.hashCode()) % SIZE;    if(buckets[index] == null)      buckets[index] = new LinkedList>();    LinkedList> bucket = buckets[index];    MapEntry pair = new MapEntry(key, value);    boolean found = false;    ListIterator> it = bucket.listIterator();    while(it.hasNext()) {      MapEntry iPair = it.next();      if(iPair.getKey().equals(key)) {        oldValue = iPair.getValue();        it.set(pair); // Replace old with new        found = true;        break;      }    }    if(!found)      buckets[index].add(pair);    return oldValue;  }  public V get(Object key) {    int index = Math.abs(key.hashCode()) % SIZE;    if(buckets[index] == null) return null;    for(MapEntry iPair : buckets[index])      if(iPair.getKey().equals(key))        return iPair.getValue();    return null;  }  public Set> entrySet() {    Set> set= new HashSet>();    for(LinkedList> bucket : buckets) {      if(bucket == null) continue;      for(MapEntry mpair : bucket)        set.add(mpair);    }    return set;  }  public static void main(String[] args) {    SimpleHashMap m =      new SimpleHashMap();    m.putAll(Countries.capitals(25));    System.out.println(m);    System.out.println(m.get("ERITREA"));    System.out.println(m.entrySet());  } } 

SimpleHashMap構(gòu)造一個(gè)hash表來存儲key,hash函數(shù)是取模運(yùn)算Math.abs(key.hashCode()) % SIZE,采用鏈表法解決hash沖突;buckets的每一個(gè)槽位對應(yīng)存放具有相同(hash后)index值的Map.Entry,如下圖所示:

JDK的HashMap的實(shí)現(xiàn)原理與之相類似,其采用鏈地址的hash表table存儲Map.Entry:

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

static class Entry implements Map.Entry {
   final K key;
   V value;
   Entry next;
   int hash;
   …
}

Map.Entry的index是對key的hashcode進(jìn)行hash后所得。當(dāng)要get key對應(yīng)的value時(shí),則對key計(jì)算其index,然后在table中取出Map.Entry即可得到,具體參看代碼:

public V get(Object key) {
   if (key == null)
       return getForNullKey();
   Entry entry = getEntry(key);

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

final Entry getEntry(Object key) {
   if (size == 0) {
       return null;
   }

   int hash = (key == null) ? 0 : hash(key);
   for (Entry 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;
}

可見,hashcode直接影響HashMap的hash函數(shù)的效率——好的hashcode會極大減少hash沖突,提高查詢性能。同時(shí),這也解釋開篇提出的兩個(gè)問題:如果自定義的類做HashMap的key,則hashcode的計(jì)算應(yīng)涵蓋構(gòu)造函數(shù)的所有字段,否則有可能得到null。


分享題目:簡單講解一下HashMap底層實(shí)現(xiàn)原理
文章來源:http://www.dlmjj.cn/article/dpssjhg.html