简单聊聊HashMap

本文探讨了HashMap的线程不安全性,详细解释了在多线程环境下可能导致的问题,并介绍了ConcurrentHashMap的改进之处。此外,阐述了HashMap解决哈希冲突的链式寻址法,以及其内部结构——数组+链表+红黑树的工作原理。最后,概述了HashMap的put、resize和get操作的源码分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说说HashMap

HashMap允许空的KV键值对。

HashMap是个非线程安全的容器,多线程情况下用 ConcurrentHashMap。

HashMap是无序的,因为哈希就是为了打散数据的。

HashMap底层初始化用的是数组+链表+红黑树。

HashMap默认大小为16,如果知道需要的容器大小,初始化的时候指定,可以避免初始化时扩容操作。

HashMap 什么场景下是线程不安全的

1、多线程操作同一资源类。一个线程增加key为A的数据,另一个线程根据key为A可能会获取不到。

2、多线程同时遇到HashMap扩容,旧数据转移到新数据的时候出现问题。

3、put操作是头插法,多线程头插入会出现循环链表,java8之后put采用尾插法。

说说ConcurrentHashMap

ConcurrentHashMap在Java 8进行了重新,Java7使用分段锁来保证线程安全和并发,Java8采用Node+CAS+Synchronized保证线程安全和并发,锁的粒度更细,只锁定链表或红黑树。

HashMap是怎么解决哈希冲突的(同题如何减少hash碰撞)

哈希冲突的解决办法有4种:

1.开放地址法:从发生冲突的那个位置,按照一定次序从Hash表中找到一个空闲的位置,把发生冲突的元素存入到这个位置。ThreadLocal用到了线性探测法来解决Hash冲突。

2.链式寻址法:通过单向链表的方式来解决哈希冲突,HashMap就是用了这个方法。

3.再哈希法:Key通过哈希函数计算得到冲突的时候,再次使用哈希函数的方法对key哈希一直运算直到不产生冲突为止。

4.建立公共溢出区:就是把Hash表分为基本表和溢出表两个部分,凡是存在冲突的元素,一律放到溢出表中

HashMap采用的是链式寻址法解决哈希冲突的,当链表转红黑树之后利用树的特性解决了哈希冲突。

说说HashMap的原理和源码

1.HashMap底层是数组+链表+红黑树,调用空参构造器初始化的时候,不会初始化数组大小,在第一次添加数据的时候进行扩容,初始化数组大小和阈值,阈值默认是0.75.

2.put元素的时候,根据哈希和容量&计算所在位置,如果位置有元素,则比较Node节点哈希值和key值是否一致,一致的话替换,不一致的时候根据当前位置是链表或红黑树进行插入。java8在链表插入进行了优化,由原来的头插入变成尾插入,避免死循环。put的时候会进行数据统计,达到阈值会进行扩容操作;链表的长度达到8并且总容量达到64,会将链表变为红黑树。

3.get元素是根据哈希计算出节点位置,然后根据链表或红黑树进行遍历,查询到一致的元素返回。

4.每次扩容都是2倍,除非到Int最大值就不扩容了,根据(e.hash & oldCap)是否为0,来判断扩容后的对象在原位置,还是原位置加上扩容的大小的位置。2倍的原因是为了方便位运算,比取模计算更快。

本人之前面试大厂的时候,这样回答过,但面试官好像不满意,希望大牛人物可以说说,该怎么回答。

put源码:

/**
 * 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.
 * 将指定值与此映射中的指定键关联。如果映射之前包含键的映射,旧的值将被替换。
 */
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

/**
 * Implements Map.put and related methods
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //未初始化或长度为0,进行扩容操作,resize()是扩容操作
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    
    //查看数组是否已经有该节点了,如果没有则新建,如果有则解决Hash冲突问题。(n - 1) & hash计算节点位置
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        //key和hash一致,新的替换旧的
        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);
                    //treeifyBin(tab, hash)长度大于等于8并且容量大于等于64就会转成红黑树
                    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;
}

treeifyBin(tab, hash)源码

/**
 * Replaces all linked nodes in bin at index for given hash unless
 * table is too small, in which case resizes instead.
 * 替换bin中所有给定哈希索引的链接节点,除非table太小,在这种情况下会调整大小。
 */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null;
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}

resize()源码

final Node<K,V>[] resize() {
    //上半截主要是为了计算新的容量大小和阈值,有三种情况
    //1.容器有数据,那就判断容器的容量是不是达到Int最大值,达到不处理,没达到左移1位,容量变为原来的2倍
    //2.容器无数据,但存在阈值,就把容器大小设置为阈值,HashMap(int initialCapacity, float loadFactor)这是有参构造器初始化HashMap会出现的情况,initialCapacity虽然设置了容量大小,但HashMap会把容量大小设置成最接近入参值的2的N次方。
    //3.容器无数据,也无阈值,空参构造器。
    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;
    
    //下半截,构建出新的,3种情况
    //1.该节点没有数据
    //2.该节点为树状
    //3.该节点为链表
    //再细化还没研究好,不显丑了
    @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;
}

get源码,通过遍历链表或者红黑树得到key一致的。

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

/**
 * Implements Map.get and related methods
 */
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

由于自身水平所限,文章难免存在遗漏或者错误,欢迎广大读者批评指正。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值