前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HashMap1.8源码解读及相关面试题解读

HashMap1.8源码解读及相关面试题解读

作者头像
envoke
发布2021-12-06 21:05:11
3040
发布2021-12-06 21:05:11
举报

文章目录

往期文章

HashMap1.7源码解读

前言

随着工作年限的增加,面试的时候对Map集合问的越来越细,本章针对jdk1.8的HashMap做详细解读,从源码层面去分析元素的添加、底层数组的扩容

提示:以下是本篇文章正文内容,下面案例可供参考

一、HashMap的数据结构

在jdk1.7中,HashMap由数组+链表实现,基于这种结构实现的HashMap在Hash碰撞较多的情况下,会导致链表长度过长,时间复杂度为O(n);效率较低。

在jdk1.8中,HashMap由数组+链表+红黑树共同构成,1.8中主要解决当链表长度过长导致查询效率降低的问题。当链表的长度达到8时,当前链表结构会转化为红黑树,当红黑树的节点数量小于6时,会从红黑树转化为链表(后面会详细分析)

二、HashMap源码解读

首先从属性出发,查看一些基本属性

代码如下(示例):

	/**
     * The default initial capacity - MUST be a power of two.
     * 默认容量:16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 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.
     * 最大容量为2^30
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

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

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

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     * 从红黑树转化为链表的阈值
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 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;
	/**
     * 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.)
     * 基本Node节点构建的数组,链表和红黑树都挂在该数组上
     */
    transient Node<K,V>[] table;

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

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

    /**
     * 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造成线程安全问题
     */
    transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     * 扩容的阈值,计算方式 = 容量 * 加载因子
     */
    int threshold;

    /**
     * The load factor for the hash table.
     * 默认的加载因子
     * @serial
     */
    final float loadFactor;

看了基本属性以后,查看基本的构造方法

    /**
     * 有参构造函数
     * @param  initialCapacity the initial capacity 初始容量
     * @param  loadFactor      the load factor 加载因子
     */
    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);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     * 有参构造,初始化容量,默认加载因子为(0.75f)
     * @param  initialCapacity the initial capacity. 初始化容量
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     * 无参构造函数,默认的容量为16,加载因子为(0.75),默认的扩容阈值为12.
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

在了解基本的属性和构造方法后,再查看核心方法 put(K key, V value);

	/**
     * 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
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

调用putVal方法时,第一个参数为根据key计算hash值,具体的计算规则如下:

代码如下(示例):

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

以案例说明HashMap中index下标的计算方法,以及hash方法的计算。

HashMap中下标位置计算
计算hash值,当key == null时,hash值为0,否则采用(h = key.hashCode()) ^ (h >>> 16)计算hash值
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
通过案例分析(h = key.hashCode()) ^ (h >>> 16);是怎么计算的
String name = "万泉";
name.hashCode() == 647074;
将hashCode值647074转化为二进制为
0000 0000 0000 1001 1101 1111 1010 0010
将值无符号右移16位,结果为:
0000 0000 0000 0000 0000 0000 0000 1001 
再将hashCode值647074与右移后的结果做异或运算(异或运算的法则为:相同为0,不同为1)
0000 0000 0000 1001 1101 1111 1010 0010 ^
0000 0000 0000 0000 0000 0000 0000 1001 =
0000 0000 0000 1001 1101 1111 1010 1011
再将这个值转化为10进制,即最后的结果 647083
下标计算为:(n - 1) & hash
n为hashmap中数组的长度,默认情况下为16
则带入我们计算的值:
(16 - 1)& 647083 = 15 & 647083
&运算的规则为:都为1才为1,否则为0
0000 0000 0000 0000 0000 0000 0000 1111   &
0000 0000 0000 1001 1101 1111 1010 1011   =
0000 0000 0000 0000 0000 0000 0000 1011
最终的计算结果为0000 0000 0000 0000 0000 0000 0000 1011
,转化为十进制为:11。
由此可得出,万泉这个字符串应该放在hashMap中下标为11的位置上。

看了hash方法的计算方式以后,继续往下观察putVal();方法的实现。

/**
     * Implements Map.put and related methods
     * Map.put方法的相关实现
     * @param hash key的hash值
     * @param key
     * @param value 需要存入的值
     * @param onlyIfAbsent 如果为true的时候,则不修改当前存在的值
     * @param evict 如果为false,当前数组为创建模式
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        // 临时数组tab
        Node<K,V>[] tab;
        // index下标处的元素
        Node<K,V> p;
        // n:数组的长度,i:数组的下标
        int n, i;
        // 判断数组是否初始化(判断方式为:全局数组 == null 或者 全局数组的长度为0)
        if ((tab = table) == null || (n = tab.length) == 0)
        	// 第一次往HashMap中存值时执行,属于懒加载方法。
            // resize()初始化数组,并返回初始化数组的长度。resize()方法也可用于扩容,后面会对该方法进行详细解析
            n = (tab = resize()).length;
        // 判断index下标是否存在元素,该index下标的计算方式在上面有描述,如果,不理解,可以按照测试案例执行
        if ((p = tab[i = (n - 1) & hash]) == null)
        	 // 数组(hash表)在index下标处没有元素时新建链表节点
            tab[i] = newNode(hash, key, value, null);
        else {
            // 数组已经初始化,并且产生了hash冲突
            // e:更新的目标值,k:p.key
            Node<K,V> e; K k;
            // 此处的p为第二个if判断时进行赋值,内容为数组(hash表)index下标处的元素
            // 产生hash冲突,并且key值相同
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                // key相等,将查询到的节点赋值给e
                e = p;
                // 判断当前p节点是否为红黑树
            else if (p instanceof TreeNode)
                // 往红黑树中放值(此处方法为红黑树的添加值的方法,由于研究hashMap的实现,就先不深入进行解析)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                // 当前节点为链表
                // 遍历数组(hash表)index下标处链表
                for (int binCount = 0; ; ++binCount) {
                    // (前面已经判断了key相等的情况)
                    if ((e = p.next) == null) {
                        // 追加到链表尾部
                        p.next = newNode(hash, key, value, null);
                        // 如果节点个数(每次遍历一个节点)超过8
                        // static final int TREEIFY_THRESHOLD = 8;
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            // 进行链表到红黑树的转化
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 下一个节点的hash值相等 && key相同就结束循环
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 遍历下一个节点
                    p = e;
                }
            }
            // 对于已存在的节点,执行覆盖操作
            if (e != null) { // existing mapping for key
                // 获取旧的value值
                V oldValue = e.value;
                // 更新value值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                // 返回旧值
                return oldValue;
            }
        }
        // 添加值的时候,modCount才会增加,覆盖的时候不会
        ++modCount;
        // 阈值检测
        if (++size > threshold)
            // 进行扩容
            resize();
        afterNodeInsertion(evict);
        return null;
    }

resize();方法解读,该方法用于初始化hash表,或者对hash表进行扩容。

/**
     * 第一次为初始化,之后为扩容
     **/
    final Node<K,V>[] resize() {
        // 获取原数组
        Node<K,V>[] oldTab = table;
        // 获取原容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // 获取旧的阈值,第一次为0
        int oldThr = threshold;
        // 新的容量以及新的阈值
        int newCap, newThr = 0;
        // 旧的容量不为0的情况下,走扩容
        if (oldCap > 0) {
            // 如果旧的容量大于最大容量
            if (oldCap >= MAXIMUM_CAPACITY) {
                // 阈值设置为Integer的最大值
                threshold = Integer.MAX_VALUE;
                // 返回旧tab并不做改变
                return oldTab;
            }
            // 将旧的容量翻倍并赋值给新的容量,并且小于最大容量 && 旧的容量要大于等于默认容量
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                // 将阈值翻倍
                newThr = oldThr << 1; // double threshold
        }
        // 旧的阈值>0,初始容量设置为阈值
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {// zero initial threshold signifies using defaults
            // 第一次创建的时候从这初始化容量为16,初始化阈值为12
            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
        table = newTab;
        // 历史tab中含有数据
        if (oldTab != null) {
            // 遍历旧tab
            for (int j = 0; j < oldCap; ++j) {
                // 声明临时变量e
                Node<K,V> e;
                // 找寻旧tab中不为null的元素,并赋值给e
                if ((e = oldTab[j]) != null) {
                    // 将旧tab[j]处的元素重置
                    oldTab[j] = null;
                    // 如果e没有下一个元素
                    if (e.next == null)
                        // 在newTab中重新计算index下标放置元素e
                        newTab[e.hash & (newCap - 1)] = e;
                    // 如果当前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;
                            // 因为oldCap的数值为2的幂次方,所以,e.hash & oldCap的结果只可能为0或另外一个固定值
                            // 当计算结果为0时,将当前链表放入到低位链表中
                            if ((e.hash & oldCap) == 0) {
                                // 低位链表的为节点为空,证明当前低位链表没有元素
                                if (loTail == null)
                                    // 低位链表头节点为当前元素e
                                    loHead = e;
                                else
                                    // 将元素e追加到低位链表尾部
                                    loTail.next = e;
                                // 坐标后移
                                loTail = e;
                            }
                            else {
                                // 当计算结果不为0时,放入到高位链表中
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                            // 从e开始,向后遍历
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            // 将低位链表放置到新tab中
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            // 将高位链表放入j+oldCap位置处
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        // 返回新创建的table
        return newTab;
    }

三、HashMap使用优化

优化一:指定泛型

集合泛型定义时,在 JDK7 及以上,使用 diamond 语法或全省略。
说明:菱形泛型,即 diamond,直接使用<>来指代前边已经指定的类型。
Java 开发手册
正例:
// diamond 方式,即<>
HashMap<String, String> userCache = new HashMap<>(16);
// 全省略方式
ArrayList<User> users = new ArrayList(10);

优化二:指定初始化容量((需要存储的元素个数 / 负载因子) + 1),避免后期容量不足,导致频繁扩容

集合初始化时,指定集合初始值大小。
说明:HashMap 使用 HashMap(int initialCapacity) 初始化,如果暂时无法确定集合大小,那么指定默
认值(16)即可。
正例:initialCapacity = (需要存储的元素个数 / 负载因子) + 1。注意负载因子(即 loader factor)默认
为 0.75,如果暂时无法确定初始值大小,请设置为 16(即默认值)。
反例:HashMap 需要放置 1024 个元素,由于没有设置容量初始大小,随着元素不断增加,容量 7 次被迫
扩大,resize 需要重建 hash 表。当放置的集合元素个数达千万级别时,不断扩容会严重影响性能。

四、相关面试题

1. 为什么重写Equals还要重写HashCode方法

为了使诸如HashMap这样的哈希表正常使用。具体规定如下: equals相等,hashcode一定相等。 equals不等,hashcode不一定不等。 hashcode不等,equals一定不等。 hashcode相等,equals不一定相等。

Object 的 hashcode 方法是本地方法,也就是用 c 或 c++ 实现的,该方法直接返回对象的内存地址,让后再转换整数。

== 比较两个对象的内存地址是否相同

Equals默认的情况下比较两个对象的内存地址

当 Equals比较对象相等以后,根据规定,hashCode值也需要相等,相应的,也需要重写HashCode方法。

2. HashMap如何避免内存泄漏问题

当以自定义对象作为HashMap的key时,如果没有重写Equals方法和HashCode方法,会导致对象一直往HashMap里面存储,并且,无法被GC垃圾回收掉,最终造成内存泄露问题。

解决方案:

在以自定义对象作为key时,需要重写Equals方法和HashCode方法。

3. HashMap1.7底层是如何实现的

采用数组+链表的形式实现,查询效率为O(n);

4. HashMapKey为null存放在什么位置

放在数组(Hash表)下标为0的位置

5. HashMap底层采用单链表还是双链表

HashMap底层为单向链表

6. 时间复杂度O(1)、O(N)、O(Logn)区别

  • O(1) 查询时间不会随着数据量的增大而增大,简单理解为一次查询即可得到结果
  • O(n) 查询时间跟数据量的增大成正比
  • O(logn) 数组增大n倍时,查询耗时增加logn,比如,数据量增大256倍时,查询时间只增加8倍

7. HashMap根据key查询的时间复杂度

首先根据key映射的对象存储在什么结构上面

  • 存储在数组上(即链表或者红黑树的头节点),时间复杂度为O(1)
  • 存储在链表上,时间复杂度为O(n);
  • 存储在红黑树上,时间复杂度为O(logn);

8. HashMap如何实现数组扩容问题

在jdk1.8中,数组扩容是以两倍容量和两倍阈值进行扩容。

9. HashMap底层是有序存放的吗?

无序、散列存放

10. 为什么不直接将key作为哈希值而是与高16位做异或运算?

降低hash冲突的概率

11. HashMap如何存放1万条key效率最高

初始化hashMap时指定容量大小为:(10000需要存储的元素个数 / 负载因子) + 1

12. HashMap1.8如何避免多线程扩容死循环问题

1.8中将原来的链表拆分为高位链表和低位链表,在重新装到扩容后的数组中 ,所以,不会造成多线程情况下扩容死循环的问题。

13. 为什么HashMap1.8需要引入红黑树

因为链表的查询效率过低,引入红黑树可以提高查询的效率,时间复杂度从O(n)降低至O(logn)

14. 为什么链表长度>8需要转红黑树?小于6转为链表,而不是都是8

在hashMap实现中可知,默认的转红黑树阈值为8,转链表的阈值为6,根据个人猜想,在节点个数过少的情况下,采用链表比红黑树的效率更高。但是为什么转红黑树的阈值和转链表的阈值不一致,是因为避免当链表长度在8左右频繁增删时,造成频繁的链表转红黑树,和红黑树转链表,消耗大量的资源,所以阈值不一致。

15. 什么情况下,需要从红黑树转换成链表存放?

当红黑树的节点数量< 6

16. HashMap底层如何降低Hash冲突概率

采用散列更加均匀的高位hash算法,取key的hashCode值,并于当前HashCode值做异或运算。

总结

HashMap是日常开发中很常用的一种集合框架,合理的使用,会提升程序的效率。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-10-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 往期文章
  • 前言
  • 一、HashMap的数据结构
  • 二、HashMap源码解读
  • 三、HashMap使用优化
  • 四、相关面试题
  • 总结
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档