欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HashMap源码解读

程序员文章站 2022-05-22 20:34:16
...


基于JDK1.8的hashMap源码

HashMap内部结构

先思考HashMap的作用:存储键值对,存储数据的
再思考计算机中存储数据的方式/结构(数据结构)
常见的数据结构:数组,链表,树形等…
猜测HashMap的数据结构是 数据 + 链表 的形式
HashMap源码解读
那么在代码中:
数组的表示:XXXX[] ——> Node table[]
单向链表的表示:
Class Node{
key
value
Node next
}
于是查看源码
1.可以看到一个Node类型的数组table

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

2.看到一个Node<K,V>对象–(可以表示单向链表):

/**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

3.再查看其他属性,先进行一个了解

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

数组的默认大小 16

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

数组大小可能不够用 – 扩容
什么时候进行扩容?
16 * 0.75=12 数组扩容的一个标准,当数组容量达到长度*阈值的值后进行扩容

/**
     * 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时,转换成红黑树结构

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

当红黑树节点小于6时,将红黑树转成链表

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

记录以下数组使用格子的数量

添加元素

putVal方法的原代码:

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

看源码:

1.数组的初始化 – resize()方法

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

HashMap源码解读
用两个变量记录数组的大小以及 新的扩容阈值大小
HashMap源码解读
将扩容阈值赋值给threashold
HashMap源码解读
初始化数组

2.添加元素之前情况

(1)数组原本的位置为空
直接添加即可
(2)数组原本的位置不为空,且下面是链表的结构
HashMap源码解读
循环遍历判断下一个节点是否为空,若不为空则添加到其下一个节点

(3)数组原本的位置不为空,且下面是红黑树的结构
HashMap源码解读
则继续向下添加红黑树节点

3.添加元素的下标如何确定

生产出一个算法,需要满足如下要求
(1) Int类型
通过对key值取hashCode()即可实现,Node对象中会存储计算出的hash值
(2) 0-15范围:数组大小的范围内
将计算出的hash值对16(数组大小)取模即可实现
源码中:
HashMap源码解读
将 n-1&hash =等价于=> 取模运算
hash值 – 32位的二进制表示
例如数组大小为16
则二进制表示为 000000000000000000000000010000
减一的二进制为 000000000000000000000000001111
与key的hash值取余,则前28位肯定为0,后四位最大为1111–15,最小为0000–0,即取值范围为0-15
所以数组长度必须为2的幂次方,才能在减去一的时候,确定最大值
(3) 尽可能充分利用数组的每一个位置
根据上述所知,数组下标通过 n-1&hash 确定,
n-1已经确定,所以为了结果尽可能分散,就是这个hash值尽可能不同
计算hash值的方法:
HashMap源码解读

/**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

将hashCode进行了位移运算
将高16位和低16位进行了异或运算,这样结果就尽可能不同了

数组的扩容

1.数组的扩容 – resize()方法

必须是2的倍数扩容
HashMap源码解读
将数组的容量进行位移操作,同时将阈值也进行位移操作
即16 ——>32 , 12 ——>24

2.扩容后,原链表节点如何进行挪动

HashMap源码解读
(1)非红黑树结构
循环遍历将链表重新打散
HashMap源码解读
将原来key的hash与旧的数组长度(并非n-1)进行取余
如果为 0 ,保持在原来的位置不同
如果不为0,加上原来的capacity
HashMap源码解读
原数组长度 000000000000000000000000010000
只有key的hash值 000100100011000000100000000110 的这个位置为0时,结果才会为0
所以这个值只可能有两个地方,一个是原下表的位置,另一个是在下标为(原下表+原容量)的位置
(2)红黑树结构
将原来的红黑树进行split切割,重新定位

总结

1.hashMap底层使用哈希表(数组+链表),当链表过长时会将链表转成红黑树以实现O(logn)时间复杂度内查找
2.hashMap的put过程
(1).对Key求hash值,然后计算下标
(2).如果没有碰撞,直接放入桶中
(3).如果碰撞了,以链表的方式直接添加到后面
(4).如果链表长度超过阈值(TREEIFY_THRESHOLD = 8),就将链表转成红黑树
(5).如果节点已经存在就替换旧值
(6).如果桶满了(容量*加载因子),就需要扩容resize
3.hash函数
(1)将高16位和低16位做一个异或运算
(2) (n-1)&hashCode得到下标
4.扩容机制
(1)容量扩充为原阿里的两倍,然后对每个节点重新计算哈希值
(2)这个值只可能存在两个地方,一个是原下标位置,另一个是在下标为(原下表+原容量)的位置
(3)当红黑树节点小于6(UNTREEIFY_THRESHOLD = 6)时,将红黑树转成链表形式