HashMap源码浅析

HashMap源码分析

本文参照了黑马程序员的HashMap视频

HashMap集合简介

HashMap是基于基于哈希表的 Map 接口的实现。允许使用null值和null键,是线程不安全的

JDK1.8之前HashMap由数组+链表组成,数组为主题,链表是为了解决哈希冲突存在的。JDK1.8以后,当链表长度大于阈值(或者红黑树的边界值,默认值为8)并且当前数组的长度大于64时,此时此索引位置上的所有数据改为使用红黑树储存。

注:将链表转换为红黑树前会判断,即使阈值大于8,但是数组长度小于64,此时并不会将链表变为红黑树,而是选择进行数组扩容。

HashMap底层的数据结构储存数据的过程

HashMap<String,Integer> map = HashMap<>();

创建HashMap对象时,在jdk8之前,构造方法中会创建一个长度为16的Entry[]用来储存键值对数据的;在jdk8以后不是在HashMap的构造方法中创建数组了,而是在put方法中创建数组Node[](准确来说是putVal方法,put方法调用putVal方法)

以以下代码为例:

HashMap<String ,Integer> map = new HashMap<>();
map.put("k1",1);
map.put("k2",2);
map.put("k3",3);
map.put("k1",4);
System.out.println(map);

1、首先putk1这个键值对,在HashMap中先将键值的原hash码无符号右移16位,再与原hash码做异或运算得到HashMap中的哈希值

return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

计算出在node数组中的索引值,如果计算出的索引空间没有数据,则直接将k1键值对储存到数组中(假设计算出的索引是3)

image-20210812154657284

2、向Hash Map中储存k2键值对,假设k2计算出的索引值也为3,此时底层会比较k2与k1的hash值是否一致,如果不一致,则再次空间上划出一个节点来储存

image-20210812164335912

3、假设向HashMap中储存k1—4键值对,首先根据k1求出的索引也肯定是3,此时比较后储存的数据k1和已经存在的数据,如果hash值相等,此时发生哈希碰撞。 那么底层会调用所属类的equals方法比较两个内容是否相等,相等则将后来的数据的value覆盖掉之前的value,不相等那么继续向下和其他的数据的key进行比较,如果都不相等则划出一个节点储存数据。

image-20210812175414002

img

说明:

  1. size表示Map中键值对的实时数量,而不是这个数组的长度
    1. threshold(临界值) = capacity(容量) * loadFactor(加载因子)。这个值是当前已占用数组长度的最大值,size超过这个临界值重新resize(扩容),扩容后的HashMap容量是之前容量的两倍。

HashMap的继承关系

image-20210812211531138

实现了两个标记接口Serializable和Cloneable表明它是可拷贝的和可序列化的

成员变量

集合的初始化容量(必须是二的n次幂)

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

为什么一定要是二的n次幂呢?因为后面计算数组索引值的时候采用(length-1) & hash的方法,类似于取余。只有当length为二的n次方时,length-1在二进制下各位数字都是1,做与运算可以达到取余的效果。此种方法可以减少碰撞,提高效率。

那么当初始化容量不是二的n次幂时呢?

HashMap的处理方式是利用位运算找到大于这个非二的n次幂的数的最近的二的n次幂

这个位运算的算法如下:

static final int tableSizeFor(int cap) {
   
   
    int n = cap - 1;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

这个算法非常巧妙,通过不断地右移与原来的数进行或运算,让每个位上都变成1,最后再加上一,就得到了最近的二的n次幂

还有个细节,就是这里的cap - 1,为什么要减一?因为当cap恰好为二的n次幂时,如果不减一,最后的出来的结果是cap的两倍,为了避免这种错误所以才减一

2、默认的负载因子,默认值为0.75

/**
 * The load factor used when none specified in constructor.
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

3、集合最大容量230

/**
 * 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.
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

4、树型阈值(当链表的值超过8会转化为红黑树)

/**
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 */
static final int TREEIFY_THRESHOLD = 8;

那么这个阈值为什么是8呢?

因为红黑树的查找平均复杂度为O(logn),而链表的查找的平均复杂度为O(n),时间效率上红黑树比链表要快,但是建立红黑树占用的空间大约是链表的两倍,对红黑树的增删都需要进行左旋右旋等操作,为了考虑时间和空间的平衡,所以设置一个阈值。

那么为什么偏偏是8呢?在HashMap的源码的注释中给出了答案

Because TreeNodes are about twice the size of regular nodes, we
* use them only when bins contain enough nodes to warrant use
* (see TREEIFY_THRESHOLD). And when they become too small (due to
* removal or resizing) they are converted back to plain bins.  In
* usages with well-distributed user hashCodes, tree bins are
* rarely used.  Ideally, under random hashCodes, the frequency of
* nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average for the default resizing
* threshold of 0.75, although with a large variance because of
* resizing granularity. Ignoring variance, the expected
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
* factorial(k)). The first values are:
*
* 0:    0.60653066
* 1:    0.30326533
* 2:    0.07581633
* 3:    0.01263606
* 4:    0.00157952
* 5:    0.00015795
* 6:    0.00001316
* 7:    0.00000094
* 8:    0.00000006
* more: less than 1 in ten million

大意就是如果hashCode的分布良好的话,那么红黑树是很少被用到的,理想情况下,链表长度符合泊松分布,注释中给出了长度为1到8的命中概率,可以看出当长度为8时概率仅为0.00000006,可以说概率是非常小了。此时再转化为红黑树,时间和空间复杂度就达到了一个非常平衡的程度。

我们可以举个例子,阈值为8时,比如现在有8个元素,用链表访问的平均查找长度为n/2,8/2=4,红黑树log(8)为3,红黑树查找效率比链表高,但是如果阈值是6,链表6/2 = 3,红黑树log(6) = 2.6,虽然速度也比链表快,但是转化为树形结构的也需要时间,所以阈值为6并不适合

5、当链表的值小于6时则会从红黑树转回链表

static final int UNTREEIFY_THRESHOLD = 6;

6、当数组长度超过64时,才会进行转化为红黑树的操作,否则进行数组扩容

/**
 * The smallest table capacity for which bins may be treeified.
 * (Otherwise the table is resized if too many nodes in a bin.)
 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
 * between resizing and treeification thresholds.
 */
static final int MIN_TREEIFY_CAPACITY = 64;

7、table数组,用来初始化储存键值对(长度需是2的n次幂

/**
 * The table, initialized on first use, and resized as
 * necessary. When allocated, length is always a power of two.
 * (We also tolerate length zero in some operations to allow
 * bootstrapping mechanics that are currently not needed.)
 */
transient Node<K,V>[] table;

8、用来存放缓存

/**
 * Holds cached entrySet(). Note that AbstractMap fields are used
 * for keySet() and values().
 */
transient Set<Map.Entry<K,V>> entrySet;

9、HashMap中存放元素的个数(重点)

/**
 * The number of key-value mappings contained in this map. 
 */
transient int size;

10、用来记录HashMap的修改次数

transient int modCount;

11、阈值

/**
 * The next size value at which to resize (capacity * load factor).
 *
 * @serial
 */
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;

下一次的数组扩容的临界值,超过了这个值数组就要进行扩容,这个值计算方式为(容量 * 负载因子)

12、哈希表的加载因子

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

用来衡量数组满的程度,默认值为0.75,第一次扩容的阈值16 * 0.75 = 12,也就是说当数组长度超过12就进行扩容。

0.75是官方给出的一个比较好的临界值,当数组里面的元素已经达到HashMap数组长度的75%时,表示这个数组太满了

构造方法

1、构造一个空的HashMap,默认初始容量(16)和负载因子(0.75)

public HashMap() {
   
   
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

2、构造一个具有指定的初始容量和默认负载因子(0.75)HashMap

public HashMap(int initialCapacity) {
   
   
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

3、构造一个具有指定的初始容量和负载因子的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;
    this.threshold = tableSizeFor(initialCapacity);
}

有人可能会问 this.threshold = tableSizeFor(initialCapacity);这一行,threshold的计算方式默认的话不是16 * 0.75 = 12嘛,如果传入的initialCapacity为9到16之间的一个数,那么返回结果就为16,thrashold的值就为16了,这不是与前面的相矛盾嘛,应该写成 this.threshold = tableSizeFor(initialCapacity) * this.loadFactor;但其实,在put方法会对threshold重新计算

4、包含另一个Map的构造函数

public HashMap(Map<? extends K, ? extends V> m) {
   
   
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
   
   
        int s = m.size();
        if (s > 0) {
   
   
            if (table == null) {
   
    // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值