HashMap源码解析

jdk1.7版本(各种小版本的源码存在一些小的差别,主要在于对key的hash计算上),对jdk1.6中的HashMap做了一些优化

HashMap概述 

  HashMap是基于哈希表的Map接口实现,提供了所有可选的映射操作,并允许使用null作为键值对。但是不保证映射的顺序,特别是它不保证顺序的恒久不变。

  HashMap不是线程安全的,这是它跟HashTable的主要区别,其次HashTable在进行Key的hash计算和index索引计算的实现也是不一样的。

  Hashtable是HashMap的线程安全版本,它的实现和HashMap实现基本一致,除了它不能包含null值的key和value,并且它在计算hash值和数组索引值的方式要稍微简单一些。对于线程安全的实现,Hashtable简单的将所有操作都标记成synchronized,即对当前实例的锁,这样容易引起一些性能问题,所以目前一般使用性能更好的ConcurrentHashMap

HashMap主要的源码解析

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

    /**
     * 默认初始化容量大小16,必须是2的幂
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大容量,必须是2的幂,且幂<=30
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 默认加载系数,可在构造函数中设置
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 空Entry数组实例,用于table未扩展时
     */
    static final Entry<?,?>[] EMPTY_TABLE = {};

    /**
     * 哈希数组,根据需要调整数组大小,长度一样必须是2的幂
     */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

    /**
     * 当前map中包含的映射键值对数量
     */
    transient int size;

    /**
     * @serial
     * 阈值,当下一个值的size到达容量*加载系数时重新调整数组大小和阈值
     * 
     * 如果元素数组table是一个EMPTY_TABLE空数组,那么阈值为初始化容量大小,直到table数组创建并扩展容量时
     * 
     */
    int threshold;

    /**
     * hash数组的加载系数
     * @serial
     */
    final float loadFactor;

    /**
     * 当map结构修改时记录此值,累加
     */
    transient int modCount;

    /**
     * The default threshold of map capacity above which alternative hashing is
     * used for String keys. Alternative hashing reduces the incidence of
     * collisions due to weak hash code calculation for String keys.
     * <p/>
     * This value may be overridden by defining the system property
     * {@code jdk.map.althashing.threshold}. A property value of {@code 1}
     * forces alternative hashing to be used at all times whereas
     * {@code -1} value ensures that alternative hashing is never used.
     * 当map容量超过默认阈值时使用替换哈希阈值(只能用于String类型的key上)
     * 替换哈希降低了字符串keys进行哈希码计算时碰撞的发生率
     * 默认替换哈希阈值为Integer.MAX_VALUE
     */
    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;

    /**
     * holds values which can't be initialized until after VM is booted.
     */
    private static class Holder {

        /**
         * table容量超出默认阈值时使用替换哈希
         */
        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;
        }
    }

    /**
     * 上面的替换哈希阈值用于计算此值
     * 哈希子,一个随机数关联当前实例用于计算key的哈希时避免哈希碰撞,如果为0则禁用替换哈希
     */
    transient int hashSeed = 0;

    /**
     * 构建一个空的hashmap并指定容量和加载系数
     */
    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;
//        初始化阈值等于容量大小,当元素数组table扩展时从新计算
        threshold = initialCapacity;
        init();
    }

    /**
     * 构造一个空hashmap并指定容量,加载系数为默认值
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 默认构造函数,容量16,加载系数为0.75
     */
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 构造一个新的hashmap并指定与参数map中一样的映射键值对
     */
    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);
    }

    
    /**
     * 其实这个方法即返回一个准确的容量大小值,因为很可能number不是2的幂
     * 所以返回一个>=number值的且是2的幂的数值
     */
    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;
    }

    /**
     * 元素数组table进行扩容达到toSize
     */
    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);
    }

    void init() {
    }

    /**
     * 初始化hashSeed的值,延迟初始化知道需要使用它时
     */
    final boolean initHashSeedAsNeeded(int capacity) {
        boolean currentAltHashing = hashSeed != 0;
        boolean useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean switching = currentAltHashing ^ useAltHashing;
        if (switching) {
            hashSeed = useAltHashing
                ? sun.misc.Hashing.randomHashSeed(this)
                : 0;
        }
        return switching;
    }

    /**
     * 返回对象哈希码
     * null对象永远将返回0
     */
    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);
    }

    /**
     * 返回哈希码h在table中的索引位置
     */
    static int indexFor(int h, int length) {
        return h & (length-1);
    }

    /**
     * 返回map键值对的数量大小
     */
    public int size() {
        return size;
    }

    /**
     * @return <tt>true</tt> if this map contains no key-value mappings
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 返回键对应的值
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

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

    /**
     * 返回key为null的值
     */
    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;
    }

    /**
     * 如果map包含此映射键则返回true
     */
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }

    /**
     * 返回指定键映射的entry对象,如果不包含则返回null
     */
    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }
        //计算出key对应hash值
        int hash = (key == null) ? 0 : hash(key);
        //根据hash定位到value在表中的索引位置,然后遍历该位置上的链表的键值对
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            //判断hash值相等且(key引用相等或key不为空时值也相等)
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

    /**
     * 在map中增加指定key映射指定的值
     * 如果map中已经包含此键,则修改键映射为指定值,并返回原映射的值
     */
    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            //判断如果当前是空则进行扩容
            inflateTable(threshold);
        }
        //如果key为null则调用单独的putForNullKey方法,将value放到数组的第一位(因为null总是指向第一位)
        if (key == null)
            return putForNullKey(value);
        //重新计算key的哈希值
        int hash = hash(key);
        //通过哈希计算出在table中锁对应的索引位置
        int i = indexFor(hash, table.length);
        //遍历指定位置的链表中是否已经存在key对应的Entry,如果有则直接修改value值并返回旧的value值
        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;
            }
        }
        //记录map中修改结构的次数
        modCount++;
        //添加对象到map中
        addEntry(hash, key, value, i);
        return null;
    }

    /**
     * 增加key为null的映射
     */
    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;
    }

    /**
     * 此方法在构造函数、克隆以及反序列化时被用来替换put方法,方法中不会调整元素数组table的大小
     * 方法调用的createEntry函数相当于addEntry函数
     */
    private void putForCreate(K key, V value) {
        int hash = null == key ? 0 : hash(key);
        int i = indexFor(hash, table.length);

        /**
         * Look for preexisting entry for key.  This will never happen for
         * clone or deserialize.  It will only happen for construction if the
         * input Map is a sorted map whose ordering is inconsistent w/ equals.
         */
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                e.value = value;
                return;
            }
        }

        createEntry(hash, key, value, i);
    }

    private void putAllForCreate(Map<? extends K, ? extends V> m) {
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            putForCreate(e.getKey(), e.getValue());
    }

    /**
     * 按照指定容量调整table大小,参数newCapacity必须是2的幂,且大于当前容量小于最大容量MAXIMUM_CAPACITY
     * 扩容将导致所有映射键值对的重新存放(rehash计算)
     */
    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];
//      重新计算hashSeed的值,并转移table元素到新的数组中(注意这里不是复制)
        transfer(newTable, initHashSeedAsNeeded(newCapacity));
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

    /**
     * Transfers all entries from current table to newTable.
     */
    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;
            }
        }
    }

    /**
     * 把指定参数map的映射键值对复制到当前map中
     * 参数map将替换调所有与当前map键相同的映射
     */
    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));
        }

        /*
         * Expand the map if the map if the number of mappings to be added
         * is greater than or equal to threshold.  This is conservative; the
         * obvious condition is (m.size() + size) >= threshold, but this
         * condition could result in a map with twice the appropriate capacity,
         * if the keys to be added overlap with the keys already in this map.
         * By using the conservative calculation, we subject ourself
         * to at most one extra resize.
         * 计算是否需要扩容
         */
        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());
    }

    /**
     * 删除指定键的map映射并返回映射的值
     */
    public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key);
        return (e == null ? null : e.value);
    }

    /**
     * 删除并返回map中指定键映射的entry,如果不存在则返回null
     */
    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;
    }

    /**
     * 删除指定键值对Entry对象
     */
    final Entry<K,V> removeMapping(Object o) {
        if (size == 0 || !(o instanceof Map.Entry))
            return null;

        Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
        Object key = entry.getKey();
        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;
            if (e.hash == hash && e.equals(entry)) {
                modCount++;
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }

        return e;
    }

    /**
     * 清空map
     */
    public void clear() {
        modCount++;
//      设置table所有值为null
        Arrays.fill(table, null);
        size = 0;
    }

    /**
     * 如果map中存在与指定value对应的key则返回true
     */
    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;
    }

    /**
     * 顾名思义
     */
    private boolean containsNullValue() {
        Entry[] tab = table;
        for (int i = 0; i < tab.length ; i++)
            for (Entry e = tab[i] ; e != null ; e = e.next)
                if (e.value == null)
                    return true;
        return false;
    }

    /**
     * 返回一个浅克隆对象,并设置对应的属性值,调用对应方法以完成完整克隆
     */
    public Object clone() {
        HashMap<K,V> result = null;
        try {
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // assert false;
        }
        if (result.table != EMPTY_TABLE) {
            result.inflateTable(Math.min(
                (int) Math.min(
                    size * Math.min(1 / loadFactor, 4.0f),
                    // we have limits...
                    HashMap.MAXIMUM_CAPACITY),
               table.length));
        }
        result.entrySet = null;
        result.modCount = 0;
        result.size = 0;
        result.init();
        result.putAllForCreate(this);

        return result;
    }

    /**
     * Entry是一个单向链表,用来解决冲突的,如果不同的key映射到哈希数组的同一个位置,就将其存放到单向链表中(插入表头)
     */
    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

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

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }
        void recordAccess(HashMap<K,V> m) {
        }
        void recordRemoval(HashMap<K,V> m) {
        }
    }

    void addEntry(int hash, K key, V value, int bucketIndex) {
        //如果当前size>=阈值且对应的索引位置上的值不为空,则进行扩容(扩容大小为当前容量的1倍)
        if ((size >= threshold) && (null != table[bucketIndex])) {
            //扩容
            resize(2 * table.length);
            //重新计算hash和该hash在新数组中的索引位置
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
        //创建并存储最终的键值对
        createEntry(hash, key, value, bucketIndex);
    }

    void createEntry(int hash, K key, V value, int bucketIndex) {
        //取出索引位置上的键值对
        Entry<K,V> e = table[bucketIndex];
        //在索引位置上存储新的键值对,且新键值对的next元素为原键值对e
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        //map大小加1
        size++;
    }
View Code

HashMap数据结构

  在java编程语言中,最基本的结构就是数组和链表。HashMap就是一个“链表散列”的数据结构(数组与链表结合)

  

  从上面的源码中可以看出HashMap的底层就是一个数组,数组中的每一个元素又是一个链表。当新建HashMap的时候就会创建一个数组。

  源码:

     /**
     * 哈希数组,根据需要调整数组大小,长度一样必须是2的幂
     */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
 
   /**
     * Entry是一个单向链表,用来解决冲突的,如果不同的key映射到哈希数    组的同一个位置,就将其存放到单向链表中(插入表头)
     */
    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;
    ....

  可以看出来数组的元素就是Entry,而Entry对象就是一个单向链表结构。

HashMap存取实现

  存储:

    /**
     * 在map中增加指定key映射指定的值
     * 如果map中已经包含此键,则修改键映射为指定值,并返回原映射的值
     */
    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            //判断如果当前是空则进行扩容
            inflateTable(threshold);
        }
        //如果key为null则调用单独的putForNullKey方法,将value放到数组的第一位(因为null总是指向第一位)
        if (key == null)
            return putForNullKey(value);
        //重新计算key的哈希值
        int hash = hash(key);
        //通过哈希计算出在table中锁对应的索引位置
        int i = indexFor(hash, table.length);
        //遍历指定位置的链表中是否已经存在key对应的Entry,如果有则直接修改value值并返回旧的value值
        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;
            }
        }
        //记录map中修改结构的次数
        modCount++;
        //添加对象到map中
        addEntry(hash, key, value, i);
        return null;
    }
View Code

其中addEntry(hash, key, value, i)是根据计算出的hash值,将key-value对放到数组的索引i的位置

    void addEntry(int hash, K key, V value, int bucketIndex) {
        //如果当前size>=阈值且对应的索引位置上的值不为空,则进行扩容(扩容大小为当前容量的1倍)
        if ((size >= threshold) && (null != table[bucketIndex])) {
            //扩容
            resize(2 * table.length);
            //重新计算hash和该hash在新数组中的索引位置
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
        //创建并存储最终的键值对
        createEntry(hash, key, value, bucketIndex);
    }

    void createEntry(int hash, K key, V value, int bucketIndex) {
        //取出索引位置上的键值对
        Entry<K,V> e = table[bucketIndex];
        //在索引位置上存储新的键值对,且新键值对的next元素为原键值对e
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        //map大小加1
        size++;
    }
View Code

  读取:

    /**
     * 返回键对应的值
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

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

    /**
     * 返回key为null的值
     */
    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;
    }
    /**
     * 返回指定键映射的entry对象,如果不包含则返回null
     */
    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }
        //计算出key对应hash值
        int hash = (key == null) ? 0 : hash(key);
        //根据hash定位到value在表中的索引位置,然后遍历该位置上的链表的键值对
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            //判断hash值相等且(key引用相等或key不为空时值也相等)
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }
View Code

从上面可以看出来读取数据也分为null和非null的处理,存储和读取数据的主要逻辑包括了key的hash计算和对应索引位置的计算

  hash和index计算:

  • hash(key)方法是根据key的hashcode重新计算一次散列,具体的算法就不说了,主要的作用在于解决hash碰撞的问题(包括变量hashSeed也是用于计算String类型的hash时避免产生哈希碰撞的)
  /**
     * 返回对象哈希码
     * null对象永远将返回0
     */
    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);
    }

前面说到过HashMap的数据结构是数组与链表的结合,所以当然希望这个HashMap里的元素位置尽量的分布均匀一些,尽量使得每个索引位置上只用一个元素。那么当使用hash计算得到索引位置时马上就能知道对应位置的元素就是我们需要的,而不需要再去遍历链表,这就大大的优化了查询速率。

  • indexFor(int h, int length)方法则是用于计算hash在table中的索引位置

对于给定的对象,只要它的hashcode相同,那么hash()进行重计算得到的值总是相同的。为了使元素分布得相对均匀,一般都是把hash值对数组长度进行取模运算。

HashMap索引位置计算:

    /**
     * 返回哈希码h在table中的索引位置
     */
    static int indexFor(int h, int length) {
        return h & (length-1);
    }

HashTable索引位置计算:

int index = (hash & 0x7FFFFFFF) % tab.length;

对比两者的索引位置计算,HashTable使用的是hash对长度取模计算,而HashMap则是hash对长度的位与计算,要知道计算机中位运算的速度远远高于其他运算(因为转换到底层就是二进制的运算)。

现在来看看h & (length-1)的巧妙之处,当length总是 2 的n次方时,h& (length-1)运算等价于对length取模,也就是h%length,但是&比%具有更高的效率。这就是为何在定义table时指定长度必须是2的幂了。

这看上去很简单,其实比较有玄机的,我们举个例子来说明:

   假设数组长度分别为15和16,优化后的hash码分别为8和9,那么&运算后的结果如下:

       h & (table.length-1)                     hash                             table.length-1

       8 & (15-1):                                 1000                   &              1110                   =                1000

       9 & (15-1):                                 1001                   &              1110                   =                1000

       -----------------------------------------------------------------------------------------------------------------------

       8 & (16-1):                                 1000                   &              1111                   =                1000

       9 & (16-1):                                 1001                   &              1111                   =                1001

  

   从上面的例子中可以看出:当它们和15-1(1110)“与”的时候,产生了相同的结果,也就是说它们会定位到数组中的同一个位置上去,这就产生了碰撞,8和9会被放到数组中的同一个位置上形成链表,那么查询的时候就需要遍历这个链 表,得到8或者9,这样就降低了查询的效率。同时,我们也可以发现,当数组长度为15的时候,hash值会与15-1(1110)进行“与”,那么 最后一位永远是0,而0001,0011,0101,1001,1011,0111,1101这几个位置永远都不能存放元素了,空间浪费相当大,更糟的是这种情况中,数组可以使用的位置比数组长度小了很多,这意味着进一步增加了碰撞的几率,减慢了查询的效率!而当数组长度为16时,即为2的n次方时,2n-1得到的二进制数的每个位上的值都为1,这使得在低位上&时,得到的和原hash的低位相同,加之hash(int h)方法对key的hashCode的进一步优化,加入了高位计算,就使得只有相同的hash值的两个值才会被放到数组中的同一个位置上形成链表。

   所以说,当数组长度为2的n次幂的时候,不同的key算得得index相同的几率较小,那么数据在数组上分布就比较均匀,也就是说碰撞的几率小,相对的,查询的时候就不用遍历某个位置上的链表,这样查询效率也就较高了。

   根据上面 put 方法的源代码可以看出,当程序试图将一个key-value对放入HashMap中时,程序首先根据该 key的 hashCode() 返回值决定该 Entry 的存储位置:如果两个 Entry 的 key 的 hashCode() 返回值相同,那它们的存储位置相同。如果这两个 Entry 的 key 通过 equals 比较返回 true,新添加 Entry 的 value 将覆盖集合中原有Entry 的 value,但key不会覆盖。如果这两个 Entry 的 key 通过 equals 比较返回 false,新添加的 Entry 将与集合中原有 Entry 形成 Entry 链,而且新添加的 Entry 位于 Entry 链的头部——具体说明继续看 addEntry() 方法的说明。

 HashMap的resize(rehash)

   当HashMap中的元素越来越多的时候,hash冲突的几率也就越来越高,因为数组的长度是固定的。所以为了提高查询的效率,就要对HashMap的数组进行扩容,数组扩容这个操作也会出现在ArrayList中,这是一个常用的操作,而在HashMap数组扩容之后,最消耗性能的点就出现了:原数组中的数据必须重新计算其在新数组中的位置,并放进去,这就是resize。

   那么HashMap什么时候进行扩容呢?当HashMap中的元素个数超过数组大小*loadFactor时,就会进行数组扩容,loadFactor的默认值为0.75,这是一个折中的取值。也就是说,默认情况下,数组大小为16,那么当HashMap中元素个数超过16*0.75=12的时候,就把数组的大小扩展为 2*16=32,即扩大一倍,然后重新计算每个元素在数组中的位置,而这是一个非常消耗性能的操作,所以如果我们已经预知HashMap中元素的个数,那么预设元素的个数能够有效的提高HashMap的性能。

 HashMap的性能参数

   HashMap 包含如下几个构造器:

   HashMap():构建一个初始容量为 16,负载因子为 0.75 的 HashMap。

   HashMap(int initialCapacity):构建一个初始容量为 initialCapacity,负载因子为 0.75 的 HashMap。

   HashMap(int initialCapacity, float loadFactor):以指定初始容量、指定的负载因子创建一个 HashMap。

   HashMap的基础构造器HashMap(int initialCapacity, float loadFactor)带有两个参数,它们是初始容量initialCapacity和加载因子loadFactor。

   initialCapacity:HashMap的最大容量,即为底层数组的长度。

   loadFactor:负载因子loadFactor定义为:散列表的实际元素数目(n)/ 散列表的容量(m)。

   负载因子衡量的是一个散列表的空间的使用程度,负载因子越大表示散列表的装填程度越高,反之愈小。对于使用链表法的散列表来说,查找一个元素的平均时间是O(1+a),因此如果负载因子越大,对空间的利用更充分,然而后果是查找效率的降低;如果负载因子太小,那么散列表的数据将过于稀疏,对空间造成严重浪费。

   HashMap的实现中,通过threshold字段来判断HashMap的最大容量:

threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);

   结合负载因子的定义公式可知,threshold就是在此loadFactor和capacity对应下允许的最大元素数目,超过这个数目就重新resize,以降低实际的负载因子。默认的的负载因子0.75是对空间和时间效率的一个平衡选择。当容量超出此最大容量时, resize后的HashMap容量是容量的两倍:

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

Fail-Fast机制

   我们知道java.util.HashMap不是线程安全的,因此如果在使用迭代器的过程中有其他线程修改了map,那么将抛出ConcurrentModificationException,这就是所谓fail-fast策略。

   这一策略在源码中的实现是通过modCount域,modCount顾名思义就是修改次数,对HashMap内容的修改都将增加这个值,那么在迭代器初始化过程中会将这个值赋给迭代器的expectedModCount。

HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

   在迭代过程中,判断modCount跟expectedModCount是否相等,如果不相等就表示已经有其他线程修改了Map:

   注意到modCount声明为volatile,保证线程之间修改的可见性。

 final Entry<K,V> nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
            current = e;
            return e;
        }

   在HashMap的API中指出:

   由所有HashMap类的“collection 视图方法”所返回的迭代器都是快速失败的:在迭代器创建之后,如果从结构上对映射进行修改,除非通过迭代器本身的 remove 方法,其他任何时间任何方式的修改,迭代器都将抛出ConcurrentModificationException。因此,面对并发的修改,迭代器很快就会完全失败,而不冒在将来不确定的时间发生任意不确定行为的风险。

   注意,迭代器的快速失败行为不能得到保证,一般来说,存在非同步的并发修改时,不可能作出任何坚决的保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。因此,编写依赖于此异常的程序的做法是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测程序错误。

参考:

http://zhangshixi.iteye.com/blog/672697

http://www.blogjava.net/DLevin/archive/2013/10/15/404984.html

原文地址:https://www.cnblogs.com/mr-long/p/5780779.html