HashMap - jdk1.7

1.底層存儲是Entry<K,V>[] table,Entry對象裏面還有個Entry<K,V> next指着下一個對象
    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;
    }
2.對哈希衝突的對象採用頭插入
    void addEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
    }
3.hashmap裏面的元素個數,大於等於負載因子*數組長度時會擴容,擴容是新建一個數組,長度爲之前的2倍,然後將原來的元素重新插入,順序是從原鏈表開頭元素遍歷插入,由於頭插法,先插入的會到鏈表後面。
4.若初始化定義元素個數爲number,則數組長度爲大於或等於number的2的冪次方的值中的最小值。例number=8,返回8;number=9,返回16。
5.數組長度爲2的冪次方的原因是,根據哈希值獲取數據下標時,不用哈希值/數組長度取模,可以用(數組長度-1) & 哈希值,這樣效率快。
6.頭插法在多線程put元素使鏈表同時擴容時,會新建2個數組,在對元素重新hash插入數組時,可能會造成環形鏈表。
7.頭插法是因爲,如果用尾插法需要遍歷到鏈表的尾部,而1.8改用尾插法是因爲它要判斷鏈表長度是否等於8來轉換紅黑數,而這個計算長度本來就要遍歷整個鏈表。
  而1.8的尾插法,還會避免1.7由於頭插法多線程Put元素造成擴容時時可能造成的死循環。
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
{
    //HashMap默認存儲元素個數爲16,必須爲2的冪次方
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //HashMap最大存儲元素個數爲2的30次方
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //負載因子,比如默認存儲元素個數爲16,當實際個數爲16*0.75=12時則擴容,新建一個長度爲32的數組(原數組長度的2倍),
    //把原來的元素按哈希值重新插入。
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //初始化一個空數組
    static final Entry<?,?>[] EMPTY_TABLE = {};

    //存儲元素的數組,長度必須爲2的冪次方
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

    //存儲元素個數
    transient int size;

    //擴容臨界值,當存儲元素個數大於等於它時則擴容。等於初始化定義的元素個數*負載因子,即capacity*loadFactor
    int threshold;

    //負載因子
    final float loadFactor;

    //改爲使用本地哈希算法(對key爲String的元素)的閾值,默認爲最大的整數。
    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;

    private static class Holder {

        //改爲使用本地哈希算法的閾值。如果在系統屬性配置了這個參數,則當初始化或擴容數組的長度大於等於這個值時,
        //會重新進行hash算法,這裏主要是對String對象,
        //使用新的hash算法sun.misc.Hashing.stringHash32((String) k),因爲String自帶的容易產生哈希碰撞。
        static final int ALTERNATIVE_HASHING_THRESHOLD;

        static {
            //如果配置了系統jdk.map.althashing.threshold則賦值,否則爲空
            String altThreshold = java.security.AccessController.doPrivileged(
                new sun.security.action.GetPropertyAction(
                    "jdk.map.althashing.threshold"));

            int threshold;
            try {
                threshold = (null != altThreshold)
                        ? Integer.parseInt(altThreshold)
                        : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;

                // disable alternative hashing if -1
                if (threshold == -1) {
                    threshold = Integer.MAX_VALUE;
                }

                if (threshold < 0) {
                    throw new IllegalArgumentException("value must be positive integer.");
                }
            } catch(IllegalArgumentException failed) {
                throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
            }

            ALTERNATIVE_HASHING_THRESHOLD = threshold;
        }
    }

    //獲得大於或等於number的2的冪次方的值中的最小值。例number=8,返回8;number=9,返回16
    private static int roundUpToPowerOf2(int number) {
        // assert number >= 0 : "number must be non-negative";
        return number >= MAXIMUM_CAPACITY
                ? MAXIMUM_CAPACITY
                : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
    }

    //初始化數組
    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);
    }

    //初始化哈希種子,並返回擴容時是否需要重新hash
    final boolean initHashSeedAsNeeded(int capacity) {
        //hashSeed初始值爲0,switching=true時纔可能會修改,所以這裏一開始爲false
        boolean currentAltHashing = hashSeed != 0;
        //sun.misc.VM.isBooted() jvm一般是啓動的所以爲true,
        //如果不設置系統屬性jdk.map.althashing.threshold,ALTERNATIVE_HASHING_THRESHOLD默認爲最大的整數,
        //所以爲false。true && false = false
        boolean useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        //如果不設置系統屬性jdk.map.althashing.threshold,則false ^ false = false
        boolean switching = currentAltHashing ^ useAltHashing;
        if (switching) {
            hashSeed = useAltHashing
                ? sun.misc.Hashing.randomHashSeed(this)
                : 0;
        }
        return switching;
    }

    //獲取哈希值
    final int hash(Object k) {
        int h = hashSeed;
        //如果hashSeed不爲0且對象是String則用另一個hash算法,因爲String自帶的hash算法容易產生哈希碰撞,
        //以防黑客精心構造哈希值相同的字符串造成鏈表過長。
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

        //通過低位與高位的各種異或,使哈希值變得更隨機,已減少哈希碰撞,jdk1.8去掉了這些複雜的異或,
        //因爲用了紅黑樹就算哈希碰撞多也影響不大。
        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";
        //比如數組長度是16,16-1是15,哈希值 & 0000 1111,則取值範圍爲0-15,這樣子效率比取模運算%效率高很多。
        //這也是數組長度必須爲2的冪次方的原因。
        return h & (length-1);
    }

    //添加元素
    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);
        //遍歷鏈表上所有的元素,如果有相等的key,則覆蓋value,然後返回oldVale
        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++;
        //無相等key則添加元素
        addEntry(hash, key, value, i);
        return null;
    }

    //當key=null時,默認該元素放在數組下標爲0的位置上
    private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }

    //數組擴容
    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);
    }

    //將舊數組上的元素遷移到新數組上,使用頭插法重新插入,但是多線程同時執行此方法時,可能會出現環形鏈表。
    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;
            }
        }
    }

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

        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }
    }
}

 

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