欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費電子書(shū)等14項超值服

開(kāi)通VIP
HashMap的實(shí)現原理和底層數據結構

 看了下Java里面有HashMap、Hashtable、HashSet三種hash集合的實(shí)現源碼,這里總結下,理解錯誤的地方還望指正

HashMap和Hashtable的區別

HashSet和HashMap、Hashtable的區別

HashMap和Hashtable的實(shí)現原理

HashMap的簡(jiǎn)化實(shí)現MyHashMap

 

HashMap和Hashtable的區別

  1. 兩者最主要的區別在于Hashtable是線(xiàn)程安全,而HashMap則非線(xiàn)程安全
    Hashtable的實(shí)現方法里面都添加了synchronized關(guān)鍵字來(lái)確保線(xiàn)程同步,因此相對而言HashMap性能會(huì )高一些,我們平時(shí)使用時(shí)若無(wú)特殊需求建議使用HashMap,在多線(xiàn)程環(huán)境下若使用HashMap需要使用Collections.synchronizedMap()方法來(lái)獲取一個(gè)線(xiàn)程安全的集合(Collections.synchronizedMap()實(shí)現原理是Collections定義了一個(gè)SynchronizedMap的內部類(lèi),這個(gè)類(lèi)實(shí)現了Map接口,在調用方法時(shí)使用synchronized來(lái)保證線(xiàn)程同步,當然了實(shí)際上操作的還是我們傳入的HashMap實(shí)例,簡(jiǎn)單的說(shuō)就是Collections.synchronizedMap()方法幫我們在操作HashMap時(shí)自動(dòng)添加了synchronized來(lái)實(shí)現線(xiàn)程同步,類(lèi)似的其它Collections.synchronizedXX方法也是類(lèi)似原理
  2. HashMap可以使用null作為key,而Hashtable則不允許null作為key
    雖說(shuō)HashMap支持null值作為key,不過(guò)建議還是盡量避免這樣使用,因為一旦不小心使用了,若因此引發(fā)一些問(wèn)題,排查起來(lái)很是費事
    HashMap以null作為key時(shí),總是存儲在table數組的第一個(gè)節點(diǎn)上
  3. HashMap是對Map接口的實(shí)現,HashTable實(shí)現了Map接口和Dictionary抽象類(lèi)
  4. HashMap的初始容量為16,Hashtable初始容量為11,兩者的填充因子默認都是0.75
    HashMap擴容時(shí)是當前容量翻倍即:capacity*2,Hashtable擴容時(shí)是容量翻倍+1即:capacity*2+1
  5. 兩者計算hash的方法不同
    Hashtable計算hash是直接使用key的hashcode對table數組的長(cháng)度直接進(jìn)行取模
    int hash = key.hashCode();int index = (hash & 0x7FFFFFFF) % tab.length;

    HashMap計算hash對key的hashcode進(jìn)行了二次hash,以獲得更好的散列值,然后對table數組長(cháng)度取摸

    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的底層實(shí)現都是數組+鏈表結構實(shí)現

HashSet和HashMap、Hashtable的區別

除開(kāi)HashMap和Hashtable外,還有一個(gè)hash集合HashSet,有所區別的是HashSet不是key value結構,僅僅是存儲不重復的元素,相當于簡(jiǎn)化版的HashMap,只是包含HashMap中的key而已

通過(guò)查看源碼也證實(shí)了這一點(diǎn),HashSet內部就是使用HashMap實(shí)現,只不過(guò)HashSet里面的HashMap所有的value都是同一個(gè)Object而已,因此HashSet也是非線(xiàn)程安全的,至于HashSet和Hashtable的區別,HashSet就是個(gè)簡(jiǎn)化的HashMap的,所以你懂的
下面是HashSet幾個(gè)主要方法的實(shí)現

  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的實(shí)現原理

HashMap和Hashtable的底層實(shí)現都是數組+鏈表結構實(shí)現的,這點(diǎn)上完全一致

添加、刪除、獲取元素時(shí)都是先計算hash,根據hash和table.length計算index也就是table數組的下標,然后進(jìn)行相應操作,下面以HashMap為例說(shuō)明下它的簡(jiǎn)單實(shí)現

  /**     * 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用來(lái)存儲數據的數組     */    transient Entry[] table;
  • HashMap的創(chuàng )建
    HashMap默認初始化時(shí)會(huì )創(chuàng )建一個(gè)默認容量為16的Entry數組,默認加載因子為0.75,同時(shí)設置臨界值為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會(huì )對null值key進(jìn)行特殊處理,總是放到table[0]位置
    put過(guò)程是先計算hash然后通過(guò)hash與table.length取摸計算index值,然后將key放到table[index]位置,當table[index]已存在其它元素時(shí),會(huì )在table[index]位置形成一個(gè)鏈表,將新添加的元素放在table[index],原來(lái)的元素通過(guò)Entry的next進(jìn)行鏈接,這樣以鏈表形式解決hash沖突問(wèn)題,當元素數量達到臨界值(capactiy*factor)時(shí),則進(jìn)行擴容,是table數組長(cháng)度變?yōu)閠able.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替換掉原來(lái)的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;            }        }    //若沒(méi)有在table[i]位置找到相同的key,則添加key到table[i]位置,新的元素總是在table[i]位置的第一個(gè)元素,原來(lái)的元素后移        modCount++;        addEntry(hash, key, value, i);        return null;    }      void addEntry(int hash, K key, V value, int bucketIndex) {    //添加key到table[bucketIndex]位置,新的元素總是在table[bucketIndex]的第一個(gè)元素,原來(lái)的元素后移    Entry<K,V> e = table[bucketIndex];        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);    //判斷元素個(gè)數是否達到了臨界值,若已達到臨界值則擴容,table長(cháng)度翻倍        if (size++ >= threshold)            resize(2 * table.length);    }

     

  • get方法
    同樣當key為null時(shí)會(huì )進(jìn)行特殊處理,在table[0]的鏈表上查找key為null的元素
    get的過(guò)程是先計算hash然后通過(guò)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類(lèi)似,計算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中并沒(méi)有公開(kāi),這個(gè)方法實(shí)現了非常重要的hashmap擴容,具體過(guò)程為:先創(chuàng )建一個(gè)容量為table.length*2的新table,修改臨界值,然后把table里面元素計算hash值并使用hash與table.length*2重新計算index放入到新的table里面
    這里需要注意下是用每個(gè)元素的hash全部重新計算index,而不是簡(jiǎn)單的把原table對應index位置元素簡(jiǎn)單的移動(dòng)到新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;
    //重新對每個(gè)元素計算index
    int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } while (e != null); } } }

     

  • clear()方法
    clear方法非常簡(jiǎn)單,就是遍歷table然后把每個(gè)位置置為null,同時(shí)修改元素個(gè)數為0
    需要注意的是clear方法只會(huì )清楚里面的元素,并不會(huì )重置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,由此可見(jiàn)HashMap的containsValue方法本質(zhì)上和普通數組和list的contains方法沒(méi)什么區別,你別指望它會(huì )像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進(jìn)行二次散列,以獲得更好的散列值
    為了更好理解這里我們可以把這兩個(gè)方法簡(jiǎn)化為 int index= key.hashCode()/table.length,以put中的方法為例可以這樣替換
    int hash = hash(key.hashCode());//計算hashint i = indexFor(hash, table.length);//計算在數組中的存儲位置//上面這兩行可以這樣簡(jiǎn)化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的簡(jiǎn)化實(shí)現MyHashMap

為了加深理解,我個(gè)人實(shí)現了一個(gè)簡(jiǎn)化版本的HashMap,注意哦,僅僅是簡(jiǎn)化版的功能并不完善,僅供參考

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;    //元素個(gè)數    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長(cháng)度取模計算key在table中的位置        return key.hashCode() % table.length;    }    public void put(Object key, Object value) {        //key為null時(shí)需要特殊處理,為簡(jiǎn)化實(shí)現忽略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位置沒(méi)有entry或者未找到重復的key,則將新key添加到table的index位置        add(index, key, value);    }    private void add(int index, Object key, Object value) {        //將新的entry放到table的index位置第一個(gè),若原來(lái)有值則以鏈表形式存放        HashEntry entry = new HashEntry(key, value, table[index]);        table[index] = entry;        //判斷size是否達到臨界值,若已達到則進(jìn)行擴容,將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,將每個(gè)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) {        //這里簡(jiǎn)化處理,忽略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;    }}

本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請點(diǎn)擊舉報。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
深入Java集合學(xué)習系列:HashMap的實(shí)現原理
Java中hashmap和hashtable的區別- 經(jīng)典
《算法導論》讀書(shū)筆記7 (散列表)
java中HashMap詳解
Java HashMap實(shí)現詳解
Java HashMap 核心源碼解讀
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導長(cháng)圖 關(guān)注 下載文章
綁定賬號成功
后續可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服

欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久