[JDK8环境下的HashMap类应用及源码分析] 看源码了解HashMap的扩容机制

🌹作者主页:青花锁 🌹简介:Java领域优质创作者🏆、Java微服务架构公号作者😄、CSDN博客专家
🌹简历模板、学习资料、面试题库、技术互助

🌹文末获取联系方式 📝

系列文章目录

[Java基础] StringBuffer 和 StringBuilder 类应用及源码分析
[Java基础] 数组应用及源码分析
[Java基础] String,分析内存地址,源码
[JDK8环境下的HashMap类应用及源码分析] 第一篇 空构造函数初始化
[JDK8环境下的HashMap类应用及源码分析] 第二篇 看源码了解HashMap的扩容机制

文章目录

  • 系列文章目录
  • 效果展示
  • 1、步骤拆解
  • 2、使用空构造函数实例化HashMap
  • 3、使用Java的反射机制,去获取threshold 、 loadFactor 、capacity值
  • 4、打印刚初始化的HashMap的元素数量、阈值、容量
    • 4.1、代码和结果
    • 4.2、查看空构造函数源代码
    • 4.3、map.size()
    • 4.4、threshold.get(map)
    • 4.5、loadFactor.get(map)
    • 4.6、capacity.invoke(map)
  • 5、添加1条数据之后打印HashMap的元素数量、阈值、容量
    • 5.1、查看map.put(100 , 100)源码
      • 5.1.1、对key做哈希
      • 5.1.2、调用putVal方法
  • 6、添加到11条数据之后打印HashMap的元素数量、阈值、容量
    • 6.1、调用map.put 10次
  • 7、添加到12条数据之后打印HashMap的元素数量、阈值、容量
    • 7.1、调用map.put 1次
  • 8、添加到13条数据之后打印HashMap的元素数量、阈值、容量
    • 8.1、调用map.put 1次
  • 关键字
  • 相关项目实现推荐:
  • [查看更多博主首页更多实战项目 >>>](https://blog.csdn.net/s445320)

效果展示

map里的元素数量:0
初始化阶段,threshold是 int类型的默认值0,此时的map下一次触发扩容的阈值:0
map下一次触发扩容的真实阈值比率:0.75
map的容量:16
------------------------------------
map里的元素数量:1
map下一次触发扩容的阈值:12
map下一次触发扩容的真实阈值比率:0.75
map的容量:16
------------------------------------
map里的元素数量:11
map下一次触发扩容的阈值:12
map下一次触发扩容的阈值比率:0.75
map的容量:16
------------------------------------
map里的元素数量:12
map下一次触发扩容的阈值:12
map下一次触发扩容的阈值比率:0.75
map的容量:16
------------------------------------
map里的元素数量:13
map下一次触发扩容的阈值:24
map下一次触发扩容的阈值比率:0.75
map的容量:32
------------------------------------
	public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException, InvocationTargetException, IllegalAccessException {

        HashMap map = new HashMap<>();

        //获取HashMap整个类
        Class<?> hashMapClszz = map.getClass();
        //获取指定属性,也可以调用getDeclaredFields()方法获取属性数组
        Field threshold =  hashMapClszz.getDeclaredField("threshold");
        //将目标属性设置为可以访问
        threshold.setAccessible(true);

        Field loadFactor = hashMapClszz.getDeclaredField("loadFactor");
        loadFactor.setAccessible(true);

        //获取指定方法,因为HashMap没有容量这个属性,但是capacity方法会返回容量值
        Method capacity = hashMapClszz.getDeclaredMethod("capacity");
        //设置目标方法为可访问
        capacity.setAccessible(true);

        //打印刚初始化的HashMap的元素数量、阈值、容量
        System.out.println("map里的元素数量:" +  map.size() );
        System.out.println("初始化阶段,threshold是 int类型的默认值0,此时的map下一次触发扩容的阈值:" +  threshold.get(map) );
        System.out.println("map下一次触发扩容的真实阈值比率:" +  loadFactor.get(map) );
        System.out.println("map的容量:" +  capacity.invoke(map) );

        System.out.println("------------------------------------");
        map.put(100 , 100);
        System.out.println("map里的元素数量:" +  map.size() );
        System.out.println("map下一次触发扩容的阈值:" +  threshold.get(map) );
        System.out.println("map下一次触发扩容的真实阈值比率:" +  loadFactor.get(map) );
        System.out.println("map的容量:" +  capacity.invoke(map) );
        
        System.out.println("------------------------------------");

        for (int i = 0; i < 10; i++) {
            map.put(i , i);
        }
        System.out.println("map里的元素数量:" +  map.size() );
        System.out.println("map下一次触发扩容的阈值:" +  threshold.get(map) );
        System.out.println("map下一次触发扩容的阈值比率:" +  loadFactor.get(map) );
        System.out.println("map的容量:" +  capacity.invoke(map) );
        System.out.println("------------------------------------");

        map.put(12 , 12);
        System.out.println("map里的元素数量:" +  map.size() );
        System.out.println("map下一次触发扩容的阈值:" +  threshold.get(map) );
        System.out.println("map下一次触发扩容的阈值比率:" +  loadFactor.get(map) );
        System.out.println("map的容量:" +  capacity.invoke(map) );
        System.out.println("------------------------------------");

        map.put(13 , 13);
        System.out.println("map里的元素数量:" +  map.size() );
        System.out.println("map下一次触发扩容的阈值:" +  threshold.get(map) );
        System.out.println("map下一次触发扩容的阈值比率:" +  loadFactor.get(map) );
        System.out.println("map的容量:" +  capacity.invoke(map) );
        System.out.println("------------------------------------");

    }

1、步骤拆解

  • 使用空构造函数实例化HashMap
  • 使用Java的反射机制,去获取threshold 、 loadFactor 、capacity值
  • 打印刚初始化的HashMap的元素数量、阈值、容量
  • 添加1条数据之后打印HashMap的元素数量、阈值、容量
  • 添加到11条数据之后打印HashMap的元素数量、阈值、容量
  • 添加到12条数据之后打印HashMap的元素数量、阈值、容量
  • 添加到13条数据之后打印HashMap的元素数量、阈值、容量

2、使用空构造函数实例化HashMap

备注:HashMap也提供有参的构造函数,可以修改loadFactor等

     HashMap map = new HashMap<>();

我们在这里创建一个HashMap对象

3、使用Java的反射机制,去获取threshold 、 loadFactor 、capacity值

查看HashMap源代码,有threshold、loadFactor属性,有capacity、loadFactor方法。后续的loadFactor我们就直接使用属性,代码也只截取了属性

	/**
     * 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;

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

	final int capacity() {
        return (table != null) ? table.length :
            (threshold > 0) ? threshold :
            DEFAULT_INITIAL_CAPACITY;
    }
	  //获取HashMap整个类
      Class<?> hashMapClszz = map.getClass();
      //获取指定属性,也可以调用getDeclaredFields()方法获取属性数组
      Field threshold =  hashMapClszz.getDeclaredField("threshold");
      //将目标属性设置为可以访问
      threshold.setAccessible(true);

      Field loadFactor = hashMapClszz.getDeclaredField("loadFactor");
      loadFactor.setAccessible(true);

      //获取指定方法,因为HashMap没有容量这个属性,但是capacity方法会返回容量值
      Method capacity = hashMapClszz.getDeclaredMethod("capacity");
      //设置目标方法为可访问
      capacity.setAccessible(true);

4、打印刚初始化的HashMap的元素数量、阈值、容量

  • 通过第3节反射获取的2个属性和1个方法,可以打印出实例化对象里属性值和方法返回结果;
  • 在操作Field、Method之前,需要设置Field、Method的权限为可访问
	//属性的语法
    Field.get(实例化对象)
	
	//方法的语法
    Method.invoke(实例化对象)

4.1、代码和结果

	 //打印刚初始化的HashMap的元素数量、阈值、容量
     System.out.println("map里的元素数量:" +  map.size() );
     System.out.println("初始化阶段,threshold是 int类型的默认值0,此时的map下一次触发扩容的阈值:" +  threshold.get(map) );
     System.out.println("map下一次触发扩容的真实阈值比率:" +  loadFactor.get(map) );
     System.out.println("map的容量:" +  capacity.invoke(map) );
     System.out.println("------------------------------------");

结果:

map里的元素数量:0
初始化阶段,threshold是 int类型的默认值0,此时的map下一次触发扩容的阈值:0
map下一次触发扩容的真实阈值比率:0.75
map的容量:16
------------------------------------

4.2、查看空构造函数源代码

查看空构造函数源代码,看看做了哪些操作

  • loadFactor赋值 0.75(下一次触发扩容的真实阈值比率)
  • threshold(在Java里int的默认值是0)
  • size(在Java里int的默认值是0)
  • table未赋值,为null
    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
    int threshold;
    final float loadFactor;
    transient int size;
    transient Node<K,V>[] table;

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

4.3、map.size()

见4.2,size此时值为0

    /**
     * Returns the number of key-value mappings in this map.
     *
     * @return the number of key-value mappings in this map
     */
    public int size() {
        return size;
    }

4.4、threshold.get(map)

见4.2,threshold此时值为0

4.5、loadFactor.get(map)

见4.2,loadFactor此时值为0.75

4.6、capacity.invoke(map)

见4.2,table此时=null,threshold=0,DEFAULT_INITIAL_CAPACITY=16
三元运算此时结果为16

	final int capacity() {
        return (table != null) ? table.length :
            (threshold > 0) ? threshold :
            DEFAULT_INITIAL_CAPACITY;
    }

5、添加1条数据之后打印HashMap的元素数量、阈值、容量

	 map.put(100 , 100);
     System.out.println("map里的元素数量:" +  map.size() );
     System.out.println("map下一次触发扩容的阈值:" +  threshold.get(map) );
     System.out.println("map下一次触发扩容的真实阈值比率:" +  loadFactor.get(map) );
     System.out.println("map的容量:" +  capacity.invoke(map) );
     System.out.println("------------------------------------");

结果:

map里的元素数量:1
map下一次触发扩容的阈值:12
map下一次触发扩容的真实阈值比率:0.75
map的容量:16
------------------------------------

5.1、查看map.put(100 , 100)源码

 /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

5.1.1、对key做哈希

	static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

5.1.2、调用putVal方法

入参 key哈希、key、value、onlyIfAbsent、evict(最后2个参数忽略)

  • size++ 在putVal里触发一次,此时值为1
  • table为null,触发resize()
  • threshold在resize()里变更为12,table的长度赋值16
	 newCap = DEFAULT_INITIAL_CAPACITY;
     newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
     threshold = newThr;
     @SuppressWarnings({"rawtypes","unchecked"})
     Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
     table = newTab;
  • loadFactor不变
 /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                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);
                        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;
    }

 	/**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = 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;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        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;
    }

6、添加到11条数据之后打印HashMap的元素数量、阈值、容量

	 for (int i = 0; i < 10; i++) {
        map.put(i , i);
     }
     System.out.println("map里的元素数量:" +  map.size() );
     System.out.println("map下一次触发扩容的阈值:" +  threshold.get(map) );
     System.out.println("map下一次触发扩容的阈值比率:" +  loadFactor.get(map) );
     System.out.println("map的容量:" +  capacity.invoke(map) );
     System.out.println("------------------------------------");

结果:

map里的元素数量:11
map下一次触发扩容的阈值:12
map下一次触发扩容的阈值比率:0.75
map的容量:16
------------------------------------

6.1、调用map.put 10次

  • size++ 在putVal里触发10次,此时值为1 + 10 = 11
  • table不为null,且元素数量为11,11<=12 为 true , 不触发resize()
  • threshold不变,还是12
  • table的长度不变,还是16

7、添加到12条数据之后打印HashMap的元素数量、阈值、容量

     map.put(12 , 12);
     System.out.println("map里的元素数量:" +  map.size() );
     System.out.println("map下一次触发扩容的阈值:" +  threshold.get(map) );
     System.out.println("map下一次触发扩容的阈值比率:" +  loadFactor.get(map) );
     System.out.println("map的容量:" +  capacity.invoke(map) );
     System.out.println("------------------------------------");

结果:

map里的元素数量:12
map下一次触发扩容的阈值:12
map下一次触发扩容的阈值比率:0.75
map的容量:16
------------------------------------

7.1、调用map.put 1次

  • size++ 在putVal里触发10次,此时值为11 + 1 = 12
  • table不为null,且元素数量为11,11<=12 为 true , 不触发resize()
  • threshold不变,还是12
  • table的长度不变,还是16

8、添加到13条数据之后打印HashMap的元素数量、阈值、容量

     map.put(13 , 13);
     System.out.println("map里的元素数量:" +  map.size() );
     System.out.println("map下一次触发扩容的阈值:" +  threshold.get(map) );
     System.out.println("map下一次触发扩容的阈值比率:" +  loadFactor.get(map) );
     System.out.println("map的容量:" +  capacity.invoke(map) );
     System.out.println("------------------------------------");

结果:

map里的元素数量:13
map下一次触发扩容的阈值:24
map下一次触发扩容的阈值比率:0.75
map的容量:32
------------------------------------

8.1、调用map.put 1次

  • size++ 在putVal里触发10次,此时值为12 + 1 = 13
  • table不为null,且元素数量为11,13 <=12 为 false , 触发resize()
  • capacity、table长度的在原基础上*2,,此时capacity、table长度为32
  • threshold= table.length * loadFactor = 32 * 0.75 = 24 , 此时threshold值为24

关键字

  1. capacity:HashMap的容量,即哈希表中桶的数量。在创建HashMap时,可以指定初始容量,如果不指定,默认为16。当哈希表中的元素数量达到容量的75%时,会触发扩容操作。

  2. threshold:HashMap的阈值,即哈希表中元素数量的上限。当哈希表中元素数量达到阈值时,会触发扩容操作。阈值的计算公式为:threshold = capacity * loadFactor。其中,loadFactor是负载因子,它的默认值为0.75。

  3. size:HashMap中元素的数量。当向HashMap中添加元素时,size会自动增加;当从HashMap中删除元素时,size会自动减少。

  4. modCount:HashMap的修改次数。当向HashMap中添加或删除元素时,modCount会自动增加。在迭代HashMap时,如果发现modCount发生变化,则会抛出ConcurrentModificationException异常,防止在迭代过程中修改HashMap导致数据不一致的问题。

相关项目实现推荐:

查看更多博主首页更多实战项目 >>>

大家点赞、收藏、关注、评论啦 、查看👇🏻👇🏻👇🏻微信公众号获取联系👇🏻👇🏻👇🏻

WX:biancheng2019

精彩专栏推荐:

构建SpringCloud alibaba项目

Vue3实战

构建SpringBoot 项目

JavaScript小游戏

Java基础

博物馆管理系统实战

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年9月2日
下一篇 2023年9月2日

相关推荐