HashMap源码解读

88 阅读5分钟

底层数据结构

JDK1.7

image.png

JDK1.8

image.png

常量分析

/**
 * The default initial capacity - MUST be a power of two.
 * 默认初始容量-必须是2的幂。
 * 2的次幂主要是计算index时使用位运算取代模运算,默认值为16
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

![image.png](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a0c65d12d40e43cd8fdcad25691b8857~tplv-k3u1fbpfcp-watermark.image?)
/**
 * 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的幂<=1<<30。
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * The load factor used when none specified in constructor.
 * 构造函数中未指定时使用的负载系数
 * 根据泊松分布,在负载因子默认为0.75,单个hash槽内元素个数为8的概率小于百万分之一,所以7作为分界线,
 * 等于7的时候不转换,大于等于8的时候才进行转换,小于等于6的时候就化为链表
 */
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.
 * 使用树而不是列表作为箱的箱计数阈值。当向至少有这么多节点的容器中添加元素时,容器将转换为树。
 * 该值必须 大于2,并且至少应为8,以符合树木移除中关于收缩后转换回普通箱的假设
 * 链表长度大于8时进行树化(还要结合数组大小来判断)
 */
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.
 * 用于在调整大小操作期间取消冻结(拆分)仓位的仓位计数阈值。应小于TREEIFY_THRESHOLD,最多为6,
 * 以便在移 除时进行收缩检测
 * 小于等于6的时候就化为链表
 */
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.
 * 可以将存储箱树化的最小表容量。(否则,如果一个bin中的节点太多,则会调整表的大小。)应至少为4
 *  TREEIFY_THRESHOLD,以避免调整大小和树化阈值之间的冲突。
 * 判断是否树化的数组大小值
 */
static final int MIN_TREEIFY_CAPACITY = 64;

JDK1.7

实例化时

HashMap hashMap=new HashMap();

微信截图_20221221143608.png

haspMapPut操作代码分析

微信截图_20221221233052.png

微信截图_20221221144315.png

微信截图_20221221144904.png

扩容方法resize()分析

微信截图_20221221145658.png

复制旧数组

微信截图_20221221150228.png

put 流程

image.png

JDK1.8

实例化时

HashMap hashMap=new HashMap();

进入代码查看空参构造方法

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

此时发现,把默认的负载系数赋值给哈希表的负载因子,JDK1.8中的空参构造与1.7中的有了不同。

public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
具体代码
}

当然你可以通过其他构造方法指定具体的初始容量(应为2的次幂1 << 4)和负载系数,可以看出实例化时并未创建具体的数组,只是指定的初始容量值和负载系数。

haspMapPut操作代码分析

hashMap.put("name","张三");

进入代码

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

可以发现调用了putVal方法,进入putVal方法

/**
* put和相关方法参数:hash–key key的hash–key-value–只放入的值。IfAbsent–如果为true,
* 则不更改现有值;exist–如果为false,则表处于创建模式。返回:上一个值,如果没有则返回null
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
   //tab:为创建的数字,Node为存Key-Value的实例,n为数组长度,i为index
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //这里判断了数组为空,说明未创建,进入resize方法获取默认的数组长度
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    
    if ((p = tab[i = (n - 1) & hash]) == null)
    //此处为true的化,说明hash出来的值在数组上的位置上还未有值,直接把Node放入数组tab[i]中
        tab[i] = newNode(hash, key, value, null);
    else { //hasp出来的值在数组位置上已经有值
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
        //条件成立,说明需要替换数组上原有的Node   
            e = p;
        else if (p instanceof TreeNode)
           //判断是否树化了,如果是进入putTreeVal方法去put值
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {//此处为数组后面有链表情况
            for (int binCount = 0; ; ++binCount) {
            // binCount表示链表长度
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                    //判断链表长度是否大于8,大于8进入树化方法,此处为判断数组是否大于64
                        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;//修改的次数
    //判断数组是否大于阈值。阈值等于初始容量*负载系数。如果空参构造则为16*0.75f=12,大于阈值则进行扩容
    if (++size > threshold)
        resize();//扩容函数
    afterNodeInsertion(evict);
    return null;
}

扩容方法resize()分析

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) {
    //长度大于0时
        if (oldCap >= MAXIMUM_CAPACITY) {
        //数组长度大于64,阈值调整为最大,仍旧返回旧的数组,没扩容
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
                 //大于初始容量,小于64,长度翻倍,为扩容准备
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
    // 初始容量设置为阈值
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
    //零初始阈值表示使用默认值
    //此处说明oldCap=0,之前put处也没有看见创建进入到resize中,使用默认值创建,既也相当于扩容0->默认值
        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)
                //这里与JDK1.7不同没有进行二次hash而是hash & (newCap -1),与高位运算,提升了性能
                //1.7需要rehash,1.8直接hash & (newCap -1)
                    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;
}

树化方法分析treeifyBin分析

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)
    //链表长度是否达到64在此处判断,没有达到时尽管链表长度大于8了还不会树化而是扩容
        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);
    }
}

HashMapGet方法分析

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

进入了getNode中方法中

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

put流程

image.png

HashMap相关问题

HashMap的底层数据结构是怎么样的?

数组+链表的形式,如果1.8中还可能是数组加红黑树

Jdk1.7和1.8有什么区别?
  1. 1.7中空参构造方法时是传入两个默认值,而1.8中则传入一个。
  2. 1.8的数据结构中多了一个数组加红黑树。
  3. 1.7使用头插法,代码的作者认为后来的值被查找的可能性更大一点,提升查找的效率。1.8使用尾插法,可以防止 链表成环。
  4. 数组里面存Key-Value的实例,在Java7叫Entry在Java8中叫Node。
  5. 扩容后1.7使用二次hash来复制旧数据,而1.8使用HashCode(Key)&(Length - 1)方法与高位进行计算。
为啥会线程不安全?

1.在1.7中,当并发执行扩容操作时会造成环形链和数据丢失的情况。 2.在1.8中,在并发执行put操作时会发生数据覆盖的情况。

有什么线程安全的类代替么?
  1. 使用Collections.synchronizedMap(Map)创建线程安全的map集合;
  2. Hashtable
  3. ConcurrentHashMap
默认初始化大小是多少?为啥大小都是2的幂?

默认值为16,2的次幂主要是计算index时使用位运算取代模运算。至于为什么没有特殊说明,实际上只要是2的次幂都可行,所以可能是经验。

HashMap的扩容方式?负载因子是多少?为什是这么多?

当数组长度达到阈值时,容器会调用方法resize()进行扩容,扩容为原有大小的2倍,负载因子为0.75f,根据泊松分布。

HashMap的主要参数都有哪些?

见上面常量说明。

HashMap是怎么处理hash碰撞的?

二次hasp 在JDK1.8中HashMap通过链式寻址法以其红黑树来解决哈希冲突的,其中红黑树是为了优化哈希表的链表过长。

hash的计算规则?

1.7中代码

image.png

1.8中代码

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