HashMap的實現原理

leonooo 8年前發布 | 17K 次閱讀 鏈表 Java開發

來自: http://www.cnblogs.com/think-in-java/p/5169660.html

1.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有做一些處理。

1.首先HashMap里面實現一個靜態內部類Entry,其重要的屬性有 key , value, next,從屬性key,value我們就能很明顯的看出來Entry就是HashMap鍵值對實現的一個基礎bean,我們上面說到HashMap的基礎就是一個線性數組,這個數組就是Entry[],Map里面的內容都保存在Entry[]里面。

2.HashMap的存取實現

既然是線性數組,為什么能隨機存取?這里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];

View Code</pre>

到這里我們輕松的理解了HashMap通過鍵值對實現存取的基本原理

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

當然HashMap里面也包含一些優化方面的實現,這里也說一下。比如:Entry[]的長度一定后,隨著map里面數據的越來越長,這樣同一個index的鏈就會很長,會不會影響性能?HashMap里面設置一個因素(也稱為因子),隨著map的size越來越大,Entry[]會以一定的規則加長長度。

3.解決hash沖突的辦法

  1. 開放定址法(線性探測再散列,二次探測再散列,偽隨機探測再散列)
  2. 再哈希法
  3. 鏈地址法
  4. 建立一個公共溢出區

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

4.實現自己的HashMap

Entry.java

 package com.tfdd.www;

/**

  • @desc
  • @author chenqm
  • @date 2016年1月29日 */ public class Entry<K,V> { private final K key; private V value; private Entry<K,V> next; public Entry(K k,V v,Entry<K,V> entry){
     key = k ;
     value = v;
     next = entry;
    
    } public V getValue() {
     return value;
    
    } public void setValue(V value) {
     this.value = value;
    
    } public Entry<K, V> getNext() {
     return next;
    
    } public void setNext(Entry<K, V> next) {
     this.next = next;
    
    } public K getKey() {
     return key;
    
    } @Override public int hashCode() {
     final int prime = 31;
     int result = 1;
     result = prime * result + ((key == null) ? 0 : key.hashCode());
     result = prime * result + ((next == null) ? 0 : next.hashCode());
     result = prime * result + ((value == null) ? 0 : value.hashCode());
     return result;
    
    } @Override public boolean equals(Object obj) {
     if (this == obj)
         return true;
     if (obj == null)
         return false;
     if (getClass() != obj.getClass())
         return false;
     Entry other = (Entry) obj;
     if (key == null) {
         if (other.key != null)
             return false;
     } else if (!key.equals(other.key))
         return false;
     if (next == null) {
         if (other.next != null)
             return false;
     } else if (!next.equals(other.next))
         return false;
     if (value == null) {
         if (other.value != null)
             return false;
     } else if (!value.equals(other.value))
         return false;
     return true;
    
    }

}

View Code</pre>

MyHashMap.java

 package com.tfdd.www;

/**

  • @desc
  • @author chenqm
  • @date 2016年1月29日 */ public class MyHashMap<K,V> { private Entry[] table;//Entry數組表 static final int DEFAULT_INITIAL_CAPACITY =16; private int size;

    public MyHashMap() {

     table = new Entry[DEFAULT_INITIAL_CAPACITY];
     size = DEFAULT_INITIAL_CAPACITY;
    

    } //獲取數組長度 public int getSize() {

     return size;
    

    } static int indexFor(int h, int length) {

     return h % length ;
    

    } public V get(K key){

     if(key==null) return null;
     int hash = key.hashCode();
     int index = indexFor(hash,table.length);
     for(Entry<K,V> e = table[index];e!=null;e = e.getNext()){
        K k = e.getKey();
        if(e.getKey().hashCode() == hash &&(key ==k ||k.equals(key))){
            return e.getValue();
        }
     }
     return null;
    

    } public V put(K key, V value){

     if(key == null) return null;
     int hash = key.hashCode();
     int index = indexFor(hash,table.length);
     for(Entry<K,V> e = table[index];e!=null;e = e.getNext()){
         K k = e.getKey();
         if(e.getKey().hashCode() == hash &&(key ==k ||k.equals(key))){
             //已經存在
             V oldValue = e.getValue();
             e.setValue(value);
             return oldValue;
         }
     }
     //不存在
     Entry<K,V> e = table[index];
     table[index] = new Entry<K,V>(key,value,e);
     return null;
    

    } }

View Code</pre>

MyHashMapTest.java  

 package com.tfdd.www;

/**

  • @desc
  • @author chenqm
  • @date 2016年1月29日 */ public class MyHashMapTest {

    public static void main(String[] args) {

     MyHashMap<String,String> map = new MyHashMap<String,String>();
     map.put("1", "1");
     map.put("2", "2");
     map.put("3", "3");
     System.out.println(map.get("2"));
     System.out.println(map.get("3"));
    

    } }

View Code</pre> </div>

 本文由用戶 leonooo 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!