探究JDK7中HashMap的底层实现原理


关键词:

负载因子 loadFactor
吞吐临界值 threshold
HashMap初始化
数据结构
put/get
resize/rehash
初始容量 initialCapacity
泊松定理
高位算法


以下问题分析基于JDK7的基础!!!
面试题:
谈谈你对HashMap中put/get方法的认识?
如果了解再谈谈HashMap的扩容机制?
默认大小是多少?
什么是负载因子(或填充比)?
什么是吞吐临界值(或阈值、threshold)?
负载因子值的大小,对HashMap有什么影响?
HashMap概述:
HashMap是基于哈希表的 Map 接口的非同步实现。此实现提供所有可选的映射操作,并允许使用null值和null键,此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

一、HashMap的数据结构


JDK7及以前版本:HashMap是数组+链表结构(即为链地址法)
此处链表为单向链表
在这里插入图片描述

table数组、Entry类

    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    transient Entry<K,V>[] table;

	static class Entry<K,V> implements Map.Entry<K,V> {
		final K key; // 存储的键
		V value; // 存储的值
		Entry<K,V> next; // 链表中指向下一个元素的指针
		final int hash; // hash值,用来确定链表上元素存储或取出的位置
		……
	}

可以看出,Entry 就是数组中的元素,每个 Map.Entry 其实就是一个 key-value 对,它持有一个指向下一个元素的引用,这就构成了链表。对于数组,扩容是必不可少的,长度每次扩大两倍。

二、HashMap的底层源码实现


2.1 HashMap源码中的重要常量

    /**
     * The default initial capacity - MUST be a power of two.
     * HashMap的默认容量
     */
    static final int DEFAULT_INITIAL_CAPACITY = 16;

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     * HashMap的最大支持容量
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     * HashMap的默认加载因子
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     * 存储元素的数组,总是2的n次幂
     * 
     */
    transient Entry<K,V>[] table;

    /**
     * The number of key-value mappings contained in this map.
     * HashMap中存储的键值对的数量
     */
    transient int size;

    /**
     * The next size value at which to resize (capacity * load factor).
     * @serial
     * 扩容的临界值,= 容量 * 填充因子
     */
    int threshold;

    /**
     * The load factor for the hash table.
     * 填充因子
     * @serial
     */
    final float loadFactor;

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     * HashMap扩容和结构改变的次数,java中快速失败机制有关
     */
    transient int modCount;

2.2 HashMap初始化

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }
    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    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);

        // Find a power of 2 >= initialCapacity
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;

        this.loadFactor = loadFactor;
        threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        table = new Entry[capacity];
        useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        init();
    }

初始化为一个长度为16的table数组

2.3 HashMap添加元素的方法put()

public V put(K key, V value) {
	// HashMap 允许存放 null 键和 null 值。
	// 当 key 为 null 时,调用 putForNullKey 方法,将 value 放置在数组第一个位置。
	if (key == null)
		return putForNullKey(value);
	// 根据 key 的 keyCode 重新计算 hash 值。
	int hash = hash(key.hashCode());
	// 搜索指定 hash 值在对应 table 中的索引。
	int i = indexFor(hash, table.length);
	// 如果 i 索引处的 Entry 不为 null,通过循环不断遍历 e 元素的下一个元素。
	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;
		}
	}
	// 如果 i 索引处的 Entry 为 null,表明此处还没有 Entry。
	modCount++;
	// 将 key、value 添加到 i 索引处。
	addEntry(hash, key, value, i);
	return null;
}

从上面的源代码中可以看出:当我们往 HashMap 中 put 元素的时候,先根据 key 的hashCode 重新计算 hash 值,根据 hash 值得到这个元素在数组中的位置(即下标),如果数组该位置上已经存放有其他元素了,那么在这个位置上的元素将以链表的形式存放,新加入的放在链头,最先加入的放在链尾。如果数组该位置上没有元素,就直接将该元素放到此数组中的该位置上。
addEntry(hash, key, value, i)方法根据计算出的 hash 值,将 key-value 对放在数组 table
的 i 索引处。addEntry 是 HashMap 提供的一个包访问权限的方法,代码如下:

    /**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.
     *
     * Subclass overrides this to alter the behavior of put method.
     */
    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);
    }

当系统决定存储 HashMap 中的 key-value 对时,完全没有考虑 Entry 中的 value,仅仅只是根据key来计算并决定每个Entry的存储位置。我们完全可以把 Map 集合中的 value 当成 key 的附属,当系统决定了 key 的存储位置之后,value 随之保存在那里即可。
hash(int h)方法根据 key 的 hashCode 重新计算一次散列。此算法加入了高位计算,防止低位不变,高位变化时,造成的 hash 冲突。

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);
}

我们可以看到在 HashMap 中 要找到某个元素,需要根据 key 的 hash 值来求得对应数组中的位置。如何计算这个置就是 hash 算法。前面说过 HashMap 的数据结构是数组和链表的结合,所以我们当然希望这个 HashMap 里面的 元素位置尽量的分布均匀些,尽量使得每个位置上的元素数量只有一个,那么当我们用 hash 算法求得这个位置的时候,马上就可以知道对应位置的元素就是我们要的,而不用再去遍历链表,这样就大大优化了查询的效率。
对于任意给定的对象,只要它的 hashCode() 返回值相同,那么程序调用 hash(int h) 方法所计算得到的 hash 码值总是相同的。我们首先想到的就是把 hash 值对数组长度取模运算,这样一来, 元素的分布相对来说是比较均匀的。但是,“模”运算的消耗还是比较大的,在 HashMap 中是这样做的:调用 indexFor(int h, int length) 方法来计算该对象应该保存在 table 数组的哪个索引处。
indexFor(int h, int length) 方法的代码如下:

    /**
     * Returns index for hash code h.
     */
    static int indexFor(int h, int length) {
        return h & (length-1);
    }

这个方法非常巧妙,它通过 h & (table.length -1) 来得到该对象的保存位,而 HashMap底层数组的长度总是 2 的 n 次方,这是 HashMap 在速度上的优化。
在 HashMap 构造器中有如下代码:

	public HashMap(int initialCapacity, float loadFactor) {
		......
		// Find a power of 2 >= initialCapacity
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;
        ......
	}

这段代码保证初始化时 HashMap 的容量总是 2 的 n 次方,即底层数组的长度总是为 2的 n 次方。当 length 总是 2 的 n 次方时,h & (length-1)运算等价于对 length 取模(length - 1的低位总是为1),也就是h & (length-1),但是&比%具有更高的效率。
当数组长度length = 16时,没有发生数据碰撞:
在这里插入图片描述
当数组长度length = 15时,发生数据碰撞的概率变大:
在这里插入图片描述
此时,h & (length-1) == h % (length-1),当hash值是大于数组长度时,高位取 0
容量是16,hash值是20,那么h & (length-1)等于 1 0 1 0 0 & 0 1 1 1 1 = 0 0 1 0 0,转为十进制等于4,即还是在原来数组0到15内,避免数组越界。

2.4 HashMap 的扩容方法resize()

那么HashMap什么时候进行扩容呢?当 HashMap 中的元素个数超过 数组大小 * loadFactor 时,就会进行数组扩容,loadFactor 的默认值为 0.75 ,这是一个折中的取值,符合泊淞分布如果loadFactor过大,说明table数组存数据非常多,密集,可能出现某一位置链表非常长,但数组上始终达不到存储的个数,从而不会触发扩容;反之,存数据很少,稀疏,导致扩容频繁,影响性能)。
也就是说,默认情况下,数组大小为 16 ,那么当 HashMap 中元素个数超过 16 * 0.75 = 12的时候,就把数组的大小扩展为 2 * 16 = 32 ,即扩大一倍,然后重新计算每个元素在新数组中的位置(rehash),而这是一个非常消耗性能的操作,所以如果我们已经预知 HashMap 中元素的个数,那么预设元素的个数能够有效的提高HashMap 的性能。
泊淞分布

Fail-Fast 机制:

在 HashMap 的 API 中指出:
由所有 HashMap 类的“collection 视图方法”所返回的迭代器都是快速失败的:在迭代器创建之后,如果从结构上对映射进行修改,除非通过迭代器本身的 remove 方法,其他任何时间任何方式的修改,迭代器都将抛出ConcurrentModificationException。因此,面对并发的修改,迭代器很快就会完全失败,而不冒在将来不确定的时间发生任意不确定行为的风险。
注意,迭代器的快速失败行为不能得到保证,一般来说,存在非同步的并发修改时,不可能作出任何坚决的保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。因此,编写依赖于此异常的程序的做法是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测程序错误。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值