HashMap1.7 1.8 HashTable 源碼分析面試考點

一部分 基礎篇

1.Hashmap 

1.1 hashMap 極其常見的一種數據格式。

  key-value 形式存放數據;

key 可以爲null ;

默認大小爲16,負載因子0.75,閾值12;

1.2 遍歷map的幾種方式: 

  public static void main(String[] args) {
        HashMap <String ,String> map = new HashMap<String, String>();
        map.put("a","1");
        map.put("b","2");
        map.put(null,"3");
        // 遍歷 map
        //1.map.entrySet()
        for(Map.Entry<String,String> entry :map.entrySet()){
            String  key =entry.getKey();
            String value =entry.getValue();
        }
       
        // 2.map.entrySet().iterator
        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, String > entry =it.next();
            String key = entry.getKey();
            String  value = entry.getValue();
        }
        //3. map.keySet()
        for(String key :map.keySet()){
            String k = key;
            String value = map.get(key);
        }
    }

1.3 map 的常用方法(結合源碼 jdk1.7)

1.3.1 繼承AbstractMap ,實現Map類

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

1.3.2 幾個重要的變量

//初始化的默認容量 16 (1<<4)1向右移動4位 二進制 10000
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 
// 最大容量不超過這個
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默認的加載因子  0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 空數組,定義是 當表沒有被初始化的時候的實例
 /**
     * An empty table instance to share when the table is not inflated.
     */
static final Entry<?,?>[] EMPTY_TABLE = {};
// 這個是 初始化的表,大小是可以調試的,但必須是2的冪
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
 // map 的size
transient int size;
//如果初始化的表爲空,那麼這個的值就是默認的容量值
//這個因素就是容量值
int threshold;

//係數  加載因子
final float loadFactor;
//  這個參數指的是 hashmap被修改的次數,和fail-fast機制
transient int modCount;

 

1.3.3 構造函數

構造函數一共有四個

1.// 初始化大小 和加載因子
public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
    }

2.初始化大小,加載因子是默認的

public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
3. 無參構造
public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }
4.  參數是個,map ,初始化大小選擇  (m原本大小/默認加載因子 ) 和(默認大小)取大的
  public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        inflateTable(threshold);

        putAllForCreate(m);
    }

1.3.4 幾個重要的方法

get()方法 

get()的思路是,先判斷是不是爲null,
如果爲null,getForNullkey(),返回key=null的value的值;
如果不是null,getEntry(),根據key的hash值從table[]數組表中查找;
定位到數組的具體位置之後,比較key值是否相等,如果key不相等,e=e.next()指向下一個;
一直找到相等的key之後,返回entry,entry.value() 就是對應的值了。

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

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

private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }
final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

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

put方法

//1 如果table==  EMPTY_TABLE,說明是第一次添加值,此時的map還沒有分配容量;調用inflateTable方法,分配容量,並且初始化數組。
//2 判斷key == null,如果是澤覆蓋原本key =null的值;
//3 計算keyhash值, 找到對應的數組位置,
//  找到對應的key值;如果有key,則覆蓋原值,並返回方法結束;
//  如果插入的key值是新的值,調用addEntry()方法,modcount++;
調用addEntry的時候,先進行是否進行擴容判斷;
如果擴容,擴容大小將是原來的兩倍或者最大值;
然後,將新的元素添加到bucketIndex的位置進去;




public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        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;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize);

        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    }
//  擴容的條件 ,a 當前個數是否大於等於闕值
                b  當前是否發生哈希碰撞

 void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

            createEntry(hash, key, value, bucketIndex);
    }
// 擴容方法  先判斷新的容量大小是不是超過最大值;新建一個數組;將原數組的值遷移到新數組中去。
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, initHashSeedAsNeeded(newCapacity));
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

putAll()方法

// 先判斷是不是入參爲0;
//在判斷 是不是沒有初始化,如果沒,就大小取 加載因子* size大小和 threshold的最大值。
//在判斷 如果闕值小於< 入參map的size
public void putAll(Map<? extends K, ? extends V> m) {
        int numKeysToBeAdded = m.size();
        if (numKeysToBeAdded == 0)
            return;

        if (table == EMPTY_TABLE) {
            inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
        }
       // 如果闕值小於size,則targetCapacity = numKeysToBeAdded / loadFactor + 1 和 newCapacity 進行比較;
       
     
        if (numKeysToBeAdded > threshold) {
    
            int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
            if (targetCapacity > MAXIMUM_CAPACITY)
                targetCapacity = MAXIMUM_CAPACITY;
            int newCapacity = table.length;
            while (newCapacity < targetCapacity)
                newCapacity <<= 1;
            if (newCapacity > table.length)
                resize(newCapacity);
        }

        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

 

remove()方法

// 判斷 key==null,如果是,求出hash值,根據hash值定位到 具體的值,如果有hash衝突,
確定好key值之後,讓當前table[i] =next。

public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key);
        return (e == null ? null : e.value);
    }

     
    
    final Entry<K,V> removeEntryForKey(Object key) {
        if (size == 0) {
            return null;
        }
        int hash = (key == null) ? 0 : hash(key);
        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;
    }

 containkey()方法

判斷size==null
判斷hash值 定位到table[]數組位置,找到具體的key值。
public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }
final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

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

hashcode的計算方法

hashcode的獲取方法 h 和table,length做且運算
static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }

final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

1.4 基於jdk1.7的

HashMap 的形式就是 單向鏈表+數組,根據hashcode確定數組位置,然後有hash衝突就單向鏈表;

HashMap  加載因子0.75 闕值是0.75*初始化容量, 擴容是原先大小的2倍。擴容條件是新插入的時候,size的長度大於闕值,並且table[i],即當前位置不null,即有hash衝突。

2.HashTable

2.1 Hashtable 特點

hashtable 與hashmap十分的相似,也是存放鍵值對,但是key 和value都不可以爲null;

2.2 HashTable 源碼解析(基於jdk1.8)

觀看hashtable 的源碼發現,其實他和hashMap相似度高了去了。您請往下看:

這是table常用的方法,放眼一看,尼瑪 這和hashMap有個雞兒區別,不行咱們得去看看源碼去:

hashTable 繼承了Dicionary<K V>這個麼個父類,然後實現的也是Map接口;這一點想想也是,HashMap和HashTable功能如此相似,肯定實現了同一個接口

幾個重要的變量:

這都是熟悉的老面孔啊,沒毛病,在hashMap中已經見過了!

private transient Entry<?,?>[] table; 數組
private int threshold;闕值
private float loadFactor;加載因子
private transient int modCount = 0; 修改次數

四個構造函數:

別鬧 怎麼參數都和HashMap一個雞兒樣,果然是吃同一個奶長大的兩兄弟!

入參 初始化容量和加載因子,但是在這裏他是直接new Entry[]數組;

  經典方法 put()

 //  第一 它加了synchronized 關鍵字,保證了線程的安全性。
//   value不可以爲null否則空指針異常
// 確定hash值
//看是否爲null,不爲null就查找是否有存在的key進行替換;
//爲null就直接添加

public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
//注意: 先計算出hash值,然後把hash值與0x7FFFFFFF與運算得到一個整數,然後確定了table索引的位置;
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }
 // 添加的時候,,首先modCount++操作;
//count是否達到闕值如果沒有就添加就ok了;
// 如果達到闕值,進行rehash()操作,rehash完成之後,重新計算index的位置
   private void addEntry(int hash, K key, V value, int index) {
        modCount++;

        Entry<?,?> tab[] = table;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();

            tab = table;
            hash = key.hashCode();
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
    }
//具體的rehash操作:newcapacity 是原先table數組長度的2倍;modcount++;

  protected void rehash() {
        int oldCapacity = table.length;
        Entry<?,?>[] oldMap = table;

        // overflow-conscious code
        int newCapacity = (oldCapacity << 1) + 1;
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            if (oldCapacity == MAX_ARRAY_SIZE)
                // Keep running with MAX_ARRAY_SIZE buckets
                return;
            newCapacity = MAX_ARRAY_SIZE;
        }
        Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

        modCount++;
        threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
        table = newMap;
        // 注意:首先它是倒着來的從數組最後一個元素開始;
        // 然後在某個元素下,把第一個entry放在了最後一個,讓第二個放在了倒數第二個以此類推。
      //相當於單鏈表反向過來了
        for (int i = oldCapacity ; i-- > 0 ;) {
            for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
                Entry<K,V> e = old;
                old = old.next;

                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
                a b c d
                
                     old=a ;e=old=a ;old=b; a.next=new[i] new[i]=a;
                            e=old=bl old=c; e.next= new[i] new[i]=e=b;
  
                     

            }
        }
    }

 

remove方法()

加鎖 計算hash值,找到對應的位置 談話pre.next=e.next或者 table[i] =next;

public synchronized V remove(Object key) {
    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K,V> e = (Entry<K,V>)tab[index];
    for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
        if ((e.hash == hash) && e.key.equals(key)) {
            modCount++;
            if (prev != null) {
                prev.next = e.next;
            } else {
                tab[index] = e.next;
            }
            count--;
            V oldValue = e.value;
            e.value = null;
            return oldValue;
        }
    }
    return null;
}

二、 比較HashMap 1.7版本和1.8版本的區別:

1.8的hashMap 不再是table數組了 而是換成了 

Node靜態類 ,有幾個組成部分包括 hash ,key,value ,next(指向下一個數組)

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

put方法:

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
     // table==null 擴容操作
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 如果沒有hash衝突 直接新生成,賦值就可以了
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
       //存在hash衝突的情況  判斷如果當前的key和hash符合 就直接存入讓e=p;
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
//  如果判斷是不是一個 treeNode,紅黑樹就直接存放到紅黑樹中去 
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
 //如果不是判斷鏈表的長度是否大於8
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {//插入尾部
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);//如果大於8就直接轉換成紅黑樹。
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

 get的方法:

// get方法
public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
// 判斷在不爲null的條件下,進行判斷第一個的值是否符合;
如果不符合,判斷下一個是不是紅黑樹,如果是紅黑樹則從紅黑中查找;
如果不是紅黑樹,則進行遍歷查找。


final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

 

好菜不怕晚 來說一下核心的擴容問題:

 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table; //現存的table數組
        int oldCap = (oldTab == null) ? 0 : oldTab.length; // 數組長度
        int oldThr = threshold; //闕值
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {// 如果已經達到最大值
                threshold = Integer.MAX_VALUE;
                return oldTab;//返回現在的數組
            }
/如果擴大到現在的2倍之後,還能小於最大值,並且原數組長度大於等於默認初始化的容量值
//就進行擴容
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)/
                newThr = oldThr << 1; // double threshold
        }
   //運行到這一步說明 小於0數組長度,那麼就是還沒初始化,則進行初始化
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
// 如果闕值也小於=0,那麼 就給他們默認的值初始化就可以了
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

 

擴容的核心功能:  

首先我們要明白 爲什麼要進行擴容?

 因爲table數組的長度是一定的,隨着不斷的往裏面put數值的時候,hash衝突肯定會越來越多,因此會影響hashmap的操作效率。那這個時候我們進行擴容就是爲了更好的平衡hash衝突。

擴容的流程是什麼?

  檢測條件,如果當前數組的長度已經大於等於 闕值(闕值 = 加載因子*初始化容量 ),並且新插入的數組位置產生了hash衝突。

 

jdk1.8的擴容做到的操作,如果沒有hash衝突 直接賦值,如果發生了衝突 如果是鏈表則進行鏈表處理。

鏈表的處理策略是:

用兩條鏈表,e.hash & oldCap,做運算判斷,這個的巧妙之處 因爲oldcap 的值是2的次冪,所以cap的二進制值是10000,100000類似的,所以 e.hash & oldCap的結果只有兩種,==0 或者==cap;=0的放到一條鏈表中,==cap的放入到另一條鏈表中,而他們的數組位置就是 table[i]即是原來的位置,和table[i+oldcap]的位置,是得更加均勻的分配到每個桶中。

 

if (oldTab != null) {

     // 遍歷數組
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {//如果oldTab[j]) !=null,說明有數值


                    oldTab[j] = null; //將其置空  等待被垃圾回收
                    if (e.next == null) // e.next == null 說明 沒有hash衝突 ,直接賦值就可以了
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode) // 如果是紅黑樹 進行紅黑樹處理
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order  // 如果不是紅黑胡,就進行鏈表處理

                       / /  這裏使用了兩條鏈表進行處理
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;

                           

                          // 關於 e.hash & oldCap 的意思分析: oldcap ,與 e.hash進行與運算,最終會有兩種結果,=0或者=oldcap

                       // 如果  e.hash & oldCap ==0 那麼就插入到loHead 鏈表中

                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);

    // 將=0的都放入到 table[j]中區,

 // 對於不等於0 的就放入到table[j+oldcap中]
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }

 

爲什麼我們只需要e.hash&cap的運算就可以了呢?

因爲jdk1,8利用了一個規律,擴容前後的hash的區別就是多了一個高位,高位是0 或者是1;cap 是2的次冪,因此他的高位肯定是1,進行e.hash&cap運算的時候,他們的結果就是=0或者=cap;

因此把元素的位置要麼放在在原來table[i],要麼在table[i+oldcap]位置;

最後注意一點,在原來table[i]位置的元素是正序的,而jdk1.7中是倒敘的。 。

 

看下jdk1.7的這部分代碼:

確定桶的位置用的策略是:

 h & (length-1); 爲什麼用length-1呢?

 length=1111,111111, length-1 =1110,11110之類的,

例如 當8 (1000)和都與length16(10000)做運算結果00000;當9 (1001)和都與length16(10000)做運算結果00000;89的桶的位置就是相同的;

當8 (1000)和都與length-1 16(1111)做運算結果1000;當9 (1001)和都與length-1 15(1111)做運算結果1001;89的桶的位置就是不同的。這樣就更好的減少hash衝突。同時不會發生數組越界的問題,因爲最大值就是length-1;

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, initHashSeedAsNeeded(newCapacity));
    table = newTable;
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}

 另外,擴容得到的鏈表是反的; 先存在1-2-3 的到的新數組中的結果就是3-2-1;

e=1; e.next = newTable[i]=null; newTable[i] = e =1;1.next=null; 

然後

e=2,e.next = newTable[i]=1; newTable[i] = e =2;2.next=1,1.next=null;

然後 

e=3; e.next=newTable[i]=2; newTable[i] = e =3;3.next=2;2.next=11.next=null;  最終結果就是 3-2-1;

 

然鵝,這就爲hashmap產生了一個致命的問題; 併發產生鏈表循環的問題;

例如: ab兩個線程同時進行擴容,

a線程執行到 e=1,e.next=table[i]的時候掛起,

線程b開始執行,線程b執行 

e=1; e.next = newTable[i]=null; newTable[i] = e =1;1.next=null; 

e=2,e.next = newTable[i]=1; newTable[i] = e =2;2.next=1,1.next=null;  此時的table[i] =2-1;b線程掛起;

線程a繼續執行:

此時e.next=table[i]就成了 e.next=table[i]=2-1;  產生循環 1-2-1;

a一直執行下去 就是  3-2-1-2-1這樣的死循環;

放get(i)方法的時候,如果找不到對應的值 就會一直sixu


void transfer(Entry[] newTable, boolean rehash) {
    int newCapacity = newTable.length;
    for (Entry<K,V> e : table) {
        while(null != e) {
            Entry<K,V> next = e.next;
            if (rehash) {
                e.hash = null == e.key ? 0 : hash(e.key);
            }
            int i = indexFor(e.hash, newCapacity);
            e.next = newTable[i];
            newTable[i] = e;
            e = next;
        }
    }
}
final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

        // 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) {
    // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
    return h & (length-1);
}

1.8相比於1.7優點:

第一 1.8解決了鏈表死循環的問題。

第二  1.8採取的數組+鏈表+紅黑樹,更好的提高了查詢性能。

當鏈表長於8的時候轉化成紅黑樹,小於轉換成鏈表。

注意的是:① hashmap被初始化的時候,數組並沒有被初始化,而是在第一次put的時候進行賦值。

②無論我們初始化穿進去的初始化大小是多少 最終都會是2的次冪.找到比當前數大的第一個2次冪。

③put的時候,1.8插入鏈表put尾部; 1.7插入鏈表put頭部; 

HashMap 是線程安全的麼?

不是的,

第一點,resize擴容會造成死循環(在1.8中已經解決了死循環的問題);

第二點 ,put操作的時候,假如ab 兩個線程 同時想插如

線程a開始執行,(key1,value1),在定位到具體的hash的位置的時候,假如此時的的插入位置的鏈表是2-3,還未插入,還未執行3.next = key1,a線程掛起;

b線程開始執行插入操作,(key2,value2),b的具體操作就是把(key2,value2的這個值插入進去;結果的鏈表 2-3-key2,對應的value2;b線程執行完成。

然後a繼續執行,a現在仍然認爲1是該鏈表的最後一個,所以插入的結果就是2-3-key2;

這樣 b插入的值就被覆蓋了。

如何保證線程的安全?

答曰:  Hashtable ConcurrentHashMap。

關於  ConcurrentHashMap,我們下期再聊!

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章