hashmap實現原理淺析

看了下JAVA裏面有HashMap、Hashtable、HashSet三種hash集合的實現源碼,這裏總結下,理解錯誤的地方還望指正 html

HashMap和Hashtable的區別 數組

HashSet和HashMap、Hashtable的區別 安全

HashMap和Hashtable的實現原理 多線程

HashMap的簡化實現MyHashMap app

 

HashMap和Hashtable的區別

  1. 二者最主要的區別在於Hashtable是線程安全,而HashMap則非線程安全
    Hashtable的實現方法裏面都添加了synchronized關鍵字來確保線程同步,所以相對而言HashMap性能會高一些,咱們平時使用時若無特殊需求建議使用HashMap,在多線程環境下若使用HashMap須要使用Collections.synchronizedMap()方法來獲取一個線程安全的集合(Collections.synchronizedMap()實現原理是Collections定義了一個SynchronizedMap的內部類,這個類實現了Map接口,在調用方法時使用synchronized來保證線程同步,固然了實際上操做的仍是咱們傳入的HashMap實例,簡單的說就是Collections.synchronizedMap()方法幫咱們在操做HashMap時自動添加了synchronized來實現線程同步,相似的其它Collections.synchronizedXX方法也是相似原理
  2. HashMap可使用null做爲key,而Hashtable則不容許null做爲key
    雖然說HashMap支持null值做爲key,不過建議仍是儘可能避免這樣使用,由於一旦不當心使用了,若所以引起一些問題,排查起來非常費事
    HashMap以null做爲key時,老是存儲在table數組的第一個節點上
  3. HashMap是對Map接口的實現,HashTable實現了Map接口和Dictionary抽象類
  4. HashMap的初始容量爲16,Hashtable初始容量爲11,二者的填充因子默認都是0.75
    HashMap擴容時是當前容量翻倍即:capacity*2,Hashtable擴容時是容量翻倍+1即:capacity*2+1
  5. 二者計算hash的方法不一樣
    Hashtable計算hash是直接使用key的hashcode對table數組的長度直接進行取模
    int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length;

    HashMap計算hash對key的hashcode進行了二次hash,以得到更好的散列值,而後對table數組長度取摸 ide

    複製代碼
    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); } static int indexFor(int h, int length) { return h & (length-1); }
    複製代碼

     

  6. HashMap和Hashtable的底層實現都是數組+鏈表結構實現

HashSet和HashMap、Hashtable的區別

除開HashMap和Hashtable外,還有一個hash集合HashSet,有所區別的是HashSet不是key value結構,僅僅是存儲不重複的元素,至關於簡化版的HashMap,只是包含HashMap中的key而已 性能

經過查看源碼也證明了這一點,HashSet內部就是使用HashMap實現,只不過HashSet裏面的HashMap全部的value都是同一個Object而已,所以HashSet也是非線程安全的,至於HashSet和Hashtable的區別,HashSet就是個簡化的HashMap的,因此你懂的
下面是HashSet幾個主要方法的實現 ui

複製代碼
private transient HashMap<E,Object> map; private static final Object PRESENT = new Object(); public HashSet() { map = new HashMap<E,Object>(); } public boolean contains(Object o) { return map.containsKey(o); } public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean remove(Object o) { return map.remove(o)==PRESENT; } public void clear() { map.clear(); }
複製代碼

 

HashMap和Hashtable的實現原理

HashMap和Hashtable的底層實現都是數組+鏈表結構實現的,這點上徹底一致 this

添加、刪除、獲取元素時都是先計算hash,根據hash和table.length計算index也就是table數組的下標,而後進行相應操做,下面以HashMap爲例說明下它的簡單實現 spa

複製代碼
/** * HashMap的默認初始容量 必須爲2的n次冪 */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * HashMap的最大容量,能夠認爲是int的最大值 */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * 默認的加載因子 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * HashMap用來存儲數據的數組 */ transient Entry[] table;
複製代碼
  • HashMap的建立
    HashMap默認初始化時會建立一個默認容量爲16的Entry數組,默認加載因子爲0.75,同時設置臨界值爲16*0.75
    複製代碼
    /** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); table = new Entry[DEFAULT_INITIAL_CAPACITY]; init(); }
    複製代碼

     

  • put方法
    HashMap會對null值key進行特殊處理,老是放到table[0]位置
    put過程是先計算hash而後經過hash與table.length取摸計算index值,而後將key放到table[index]位置,當table[index]已存在其它元素時,會在table[index]位置造成一個鏈表,將新添加的元素放在table[index],原來的元素經過Entry的next進行連接,這樣以鏈表形式解決hash衝突問題,當元素數量達到臨界值(capactiy*factor)時,則進行擴容,是table數組長度變爲table.length*2
  • 複製代碼
    public V put(K key, V value) { if (key == null) return putForNullKey(value); //處理null值 int hash = hash(key.hashCode());//計算hash int i = indexFor(hash, table.length);//計算在數組中的存儲位置 //遍歷table[i]位置的鏈表,查找相同的key,若找到則使用新的value替換掉原來的oldValue並返回oldValue for (Entry<K,V> 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; } } //若沒有在table[i]位置找到相同的key,則添加key到table[i]位置,新的元素老是在table[i]位置的第一個元素,原來的元素後移 modCount++; addEntry(hash, key, value, i); return null; } void addEntry(int hash, K key, V value, int bucketIndex) { //添加key到table[bucketIndex]位置,新的元素老是在table[bucketIndex]的第一個元素,原來的元素後移 Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); //判斷元素個數是否達到了臨界值,若已達到臨界值則擴容,table長度翻倍 if (size++ >= threshold) resize(2 * table.length); }
    複製代碼

     

  • get方法
    一樣當key爲null時會進行特殊處理,在table[0]的鏈表上查找key爲null的元素
    get的過程是先計算hash而後經過hash與table.length取摸計算index值,而後遍歷table[index]上的鏈表,直到找到key,而後返回
    複製代碼
    public V get(Object key) { if (key == null) return getForNullKey();//處理null值 int hash = hash(key.hashCode());//計算hash //在table[index]遍歷查找key,若找到則返回value,找不到返回null 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; }
    複製代碼

     

  • remove方法
    remove方法和put get相似,計算hash,計算index,而後遍歷查找,將找到的元素從table[index]鏈表移除
    複製代碼
    public V remove(Object key) { Entry<K,V> e = removeEntryForKey(key); return (e == null ? null : e.value); } final Entry<K,V> removeEntryForKey(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); int i = indexFor(hash, table.length); Entry<K,V> prev = table[i]; Entry<K,V> e = prev; while (e != null) { Entry<K,V> next = e.next; Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { modCount++; size--; if (prev == e) table[i] = next; else prev.next = next; e.recordRemoval(this); return e; } prev = e; e = next; } return e; }
    複製代碼

     

  • resize方法
    resize方法在hashmap中並無公開,這個方法實現了很是重要的hashmap擴容,具體過程爲:先建立一個容量爲table.length*2的新table,修改臨界值,而後把table裏面元素計算hash值並使用hash與table.length*2從新計算index放入到新的table裏面
    這裏須要注意下是用每一個元素的hash所有從新計算index,而不是簡單的把原table對應index位置元素簡單的移動到新table對應位置
    複製代碼
    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); } 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); } } }
    複製代碼

     

  • clear()方法
    clear方法很是簡單,就是遍歷table而後把每一個位置置爲null,同時修改元素個數爲0
    須要注意的是clear方法只會清楚裏面的元素,並不會重置capactiy
    複製代碼
    public void clear() { modCount++; Entry[] tab = table; for (int i = 0; i < tab.length; i++) tab[i] = null; size = 0; }
    複製代碼

     

  • containsKey和containsValue
    containsKey方法是先計算hash而後使用hash和table.length取摸獲得index值,遍歷table[index]元素查找是否包含key相同的值
    複製代碼
    public boolean containsKey(Object key) { return getEntry(key) != null; } final Entry<K,V> getEntry(Object key) { int hash = (key == null) ? 0 : 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 != null && key.equals(k)))) return e; } return null; }
    複製代碼

    containsValue方法就比較粗暴了,就是直接遍歷全部元素直到找到value,因而可知HashMap的containsValue方法本質上和普通數組和list的contains方法沒什麼區別,你別期望它會像containsKey那麼高效

    複製代碼
    public boolean containsValue(Object value) { if (value == null) return containsNullValue(); Entry[] tab = table; for (int i = 0; i < tab.length ; i++) for (Entry e = tab[i] ; e != null ; e = e.next) if (value.equals(e.value)) return true; return false; }
    複製代碼

     

  • hash和indexFor
    indexFor中的h & (length-1)就至關於h%length,用於計算index也就是在table數組中的下標
    hash方法是對hashcode進行二次散列,以得到更好的散列值
    爲了更好理解這裏咱們能夠把這兩個方法簡化爲 int index= key.hashCode()/table.length,以put中的方法爲例能夠這樣替換
    int hash = hash(key.hashCode());//計算hash int i = indexFor(hash, table.length);//計算在數組中的存儲位置 //上面這兩行能夠這樣簡化 int i = key.key.hashCode()%table.length;

     

  • 複製代碼
    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); } static int indexFor(int h, int length) { return h & (length-1); }
    複製代碼

     

HashMap的簡化實現MyHashMap

爲了加深理解,我我的實現了一個簡化版本的HashMap,注意哦,僅僅是簡化版的功能並不完善,僅供參考

複製代碼
package cn.lzrabbit.structure; /** * Created by rabbit on 14-5-4. */ public class MyHashMap { //默認初始化大小 16 private static final int DEFAULT_INITIAL_CAPACITY = 16; //默認負載因子 0.75 private static final float DEFAULT_LOAD_FACTOR = 0.75f; //臨界值 private int threshold; //元素個數 private int size; //擴容次數 private int resize; private HashEntry[] table; public MyHashMap() { table = new HashEntry[DEFAULT_INITIAL_CAPACITY]; threshold = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); size = 0; } private int index(Object key) { //根據key的hashcode和table長度取模計算key在table中的位置 return key.hashCode() % table.length; } public void put(Object key, Object value) { //key爲null時須要特殊處理,爲簡化實現忽略null值 if (key == null) return; int index = index(key); //遍歷index位置的entry,若找到重複key則更新對應entry的值,而後返回 HashEntry entry = table[index]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { entry.setValue(value); return; } entry = entry.getNext(); } //若index位置沒有entry或者未找到重複的key,則將新key添加到table的index位置  add(index, key, value); } private void add(int index, Object key, Object value) { //將新的entry放到table的index位置第一個,若原來有值則以鏈表形式存放 HashEntry entry = new HashEntry(key, value, table[index]); table[index] = entry; //判斷size是否達到臨界值,若已達到則進行擴容,將table的capacicy翻倍 if (size++ >= threshold) { resize(table.length * 2); } } private void resize(int capacity) { if (capacity <= table.length) return; HashEntry[] newTable = new HashEntry[capacity]; //遍歷原table,將每一個entry都從新計算hash放入newTable中 for (int i = 0; i < table.length; i++) { HashEntry old = table[i]; while (old != null) { HashEntry next = old.getNext(); int index = index(old.getKey()); old.setNext(newTable[index]); newTable[index] = old; old = next; } } //用newTable替table table = newTable; //修改臨界值 threshold = (int) (table.length * DEFAULT_LOAD_FACTOR); resize++; } public Object get(Object key) { //這裏簡化處理,忽略null值 if (key == null) return null; HashEntry entry = getEntry(key); return entry == null ? null : entry.getValue(); } public HashEntry getEntry(Object key) { HashEntry entry = table[index(key)]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { return entry; } entry = entry.getNext(); } return null; } public void remove(Object key) { if (key == null) return; int index = index(key); HashEntry pre = null; HashEntry entry = table[index]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { if (pre == null) table[index] = entry.getNext(); else pre.setNext(entry.getNext()); //若是成功找到並刪除,修改size size--; return; } pre = entry; entry = entry.getNext(); } } public boolean containsKey(Object key) { if (key == null) return false; return getEntry(key) != null; } public int size() { return this.size; } public void clear() { for (int i = 0; i < table.length; i++) { table[i] = null; } this.size = 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("size:%s capacity:%s resize:%s\n\n", size, table.length, resize)); for (HashEntry entry : table) { while (entry != null) { sb.append(entry.getKey() + ":" + entry.getValue() + "\n"); entry = entry.getNext(); } } return sb.toString(); } } class HashEntry { private final Object key; private Object value; private HashEntry next; public HashEntry(Object key, Object value, HashEntry next) { this.key = key; this.value = value; this.next = next; } public Object getKey() { return key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public HashEntry getNext() { return next; } public void setNext(HashEntry next) { this.next = next; } }
複製代碼
相關文章
相關標籤/搜索