HashMap、HashTable、HashSet的實現原理和底層數據結構

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數組長度取摸

    複製代碼

    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幾個主要方法的實現

複製代碼

    HashMap<E,Object>=  HashMap<E,Object> map.put(e, PRESENT)== map.put(e, PRESENT)== map.remove(o)==

複製代碼

 

HashMap和Hashtable的實現原理

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

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

複製代碼

  /**
     * 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對應位置

    複製代碼

     resize(= oldCapacity = (oldCapacity ==== == ()(newCapacity *= newCapacity = ( j = ; j < src.; j++<K,V> e = (e != = <K,V>  = i ==== (e !=

    複製代碼

     

  • 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 & (-)就相當於h,用於計算也就是在table數組中的下標
    hash方法是對hashcode進行二次散列,以獲得更好的散列值
    爲了更好理解這裏我們可以把這兩個方法簡化爲  = key.hashCode()/table.,以put中的方法爲例可以這樣替換
    int hash = hash(key.hashCode());//計算hashint 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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章