HashMap源码简单解读

本文会从JDK1.7和1.8两个版本的hashmap着手分析,其中主要是分析了hashMap的初始化过程,putVal过程,扩容过程,树化过程。不到之处,欢迎大家指正。 如果想仔细了解红黑树相关操作,敬请移步HashMap中的红黑树_徐乙的博客-CSDN博客

我们先带着几个简单的常用面试问题入手:

1.hashmap为什么规定容量是2的n次幂

2.hashmap中树化的阈值为什么是8

3.JDK1.7的头插法会产生,那关于头插法为什么引起回环

4.hashmap中的hash()方法 为什么重新实现 为什么不直接使用key的hashcode

5.hashmap是怎么实现扩容的,具体步骤大致是什么。

先从hashmap的相关变量开始

    //默认的初始化长度 16  <<左移  >>>无符号右移
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
    //最大容量 2^30
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //默认加载因子 0.75 扩容
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //树化 节点链表长度 8
    static final int TREEIFY_THRESHOLD = 8;
    //反树化 节点链表长度 6    降结构  红黑树-->数组加链表
    static final int UNTREEIFY_THRESHOLD = 6;
    //树化的最小容量
    static final int MIN_TREEIFY_CAPACITY = 64;
    //初始化的负载容量   以默认为例 16 0.75 负载容量为12
    int threshold;
    //负载因子
    static  float loadFactor = 0.75f;



    //节点数组 不参与序列化
    transient HhashMap.Node<K,V>[] table;
    //一种遍历方式
    transient Set<Map.Entry<K,V>> entrySet;
    //有几个键值对
    transient int size;
    //类似hashmap的乐观锁 jdk在面对迭代遍历的时候为了避免不确定性而采取的快速失败原则
    // 如果在迭代过程中发现hashmap被remove()add()则concurrentModificationException
    transient int modCount;

//节点  next指针 表示数组中节点 是链表头 每一个数组节点下面都是可以挂载一条链表的
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;
        }

hashmap的构造函数  先是做了一些简单判断 然后进入到了tableSizeFor(initialCapacity)方法

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;
//注:此时修改的值 是扩容容量 threshold 不是hashmap容量capacity
        this.threshold = tableSizeFor(initialCapacity);
    }

根据cap大小 来进行移位操作 找出 刚好比cap大的 2的n次幂
例如传进来 15 n=14  n = n | (n>>>1)  即 n = 1110|0111 = 1111  最后返回的都是1111 n+1= 16  其实只看最高位 只要首位是1 经过移位之后 后面的位就可能都会被填充满 例如100 111, 1011 1111。   因此如果自己设置初始化容量为15 那么hashmap会自动创建一个16的容量
static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

那么设计者 为什么故意这么设计呢 把hashmap的容量都设置为2的几次方 

主要是因为 hashmap在putval中的一步操作 

tab[i = (n - 1) & hash

这一步主要是用来查找当前元素放入hashmap时放在数组的具体位置   以n=16为例

1111 & xxxxxxxxx1010  或 1111 & xxxxxxxxxx1011 此时 运算后的结果是 1111将hash的数字特征做了全部存储  但是相反

如果n = 15   n-1的二进制 1110  此时 1110 & xxxxxxxxxx1010  和 1110 & xxxxxxxxxxx1011 结果都是 1010 放入元素发生了碰撞

 此时只是规定了shreshold 但是实际的初始化空间还没开始 第一次为hashmap准备初始化空间发生在hashmap声明后的第一次putval操作。    截取一段putval的代码 :

我们传入15作为initcapacity   hashmap帮我们 采纳16作为shreshold   但是此时hashmap只是生命出来 初始化了一些参数 实际里面没有元素 所以tab.length=0毋庸置疑  

    final HashMap.Node<K,V>[] resize() {
        HashMap.Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length; //未放入元素 长度为0
        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) // 但是shreshold被设置成了16>0
            newCap = oldThr;//新的容量被shreshold代替cap = 16
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) { //重新初始化参数shrehold 重新设置为16*0.75 = 12
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;

至此此时第一个问题回答完毕。

现在来解决第二个问题  为什么树化的容量是8或者说为什么要引入红黑树。

hashmap1.8的源码中有这样一段注释

/*
     * Implementation notes.
     *
     * This map usually acts as a binned (bucketed) hash table, but
     * when bins get too large, they are transformed into bins of
     * TreeNodes, each structured similarly to those in
     * java.util.TreeMap. Most methods try to use normal bins, but
     * relay to TreeNode methods when applicable (simply by checking
     * instanceof a node).  Bins of TreeNodes may be traversed and
     * used like any others, but additionally support faster lookup
     * when overpopulated. However, since the vast majority of bins in
     * normal use are not overpopulated, checking for existence of
     * tree bins may be delayed in the course of table methods.
     *
     * Tree bins (i.e., bins whose elements are all TreeNodes) are
     * ordered primarily by hashCode, but in the case of ties, if two
     * elements are of the same "class C implements Comparable<C>",
     * type then their compareTo method is used for ordering. (We
     * conservatively check generic types via reflection to validate
     * this -- see method comparableClassFor).  The added complexity
     * of tree bins is worthwhile in providing worst-case O(log n)
     * operations when keys either have distinct hashes or are
     * orderable, Thus, performance degrades gracefully under
     * accidental or malicious usages in which hashCode() methods
     * return values that are poorly distributed, as well as those in
     * which many keys share a hashCode, so long as they are also
     * Comparable. (If neither of these apply, we may waste about a
     * factor of two in time and space compared to taking no
     * precautions. But the only known cases stem from poor user
     * programming practices that are already so slow that this makes
     * little difference.)
     *
     * Because TreeNodes are about twice the size of regular nodes, we
     * use them only when bins contain enough nodes to warrant use
     * (see TREEIFY_THRESHOLD). And when they become too small (due to
     * removal or resizing) they are converted back to plain bins.  In
     * usages with well-distributed user hashCodes, tree bins are
     * rarely used.  Ideally, under random hashCodes, the frequency of
     * nodes in bins follows a Poisson distribution
     * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
     * parameter of about 0.5 on average for the default resizing
     * threshold of 0.75, although with a large variance because of
     * resizing granularity. Ignoring variance, the expected
     * occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
     * factorial(k)). The first values are:
     *
     * 0:    0.60653066
     * 1:    0.30326533
     * 2:    0.07581633
     * 3:    0.01263606
     * 4:    0.00157952
     * 5:    0.00015795
     * 6:    0.00001316
     * 7:    0.00000094
     * 8:    0.00000006
     * more: less than 1 in ten million
     *
     * The root of a tree bin is normally its first node.  However,
     * sometimes (currently only upon Iterator.remove), the root might
     * be elsewhere, but can be recovered following parent links
     * (method TreeNode.root()).
     *
     * All applicable internal methods accept a hash code as an
     * argument (as normally supplied from a public method), allowing
     * them to call each other without recomputing user hashCodes.
     * Most internal methods also accept a "tab" argument, that is
     * normally the current table, but may be a new or old one when
     * resizing or converting.
     *
     * When bin lists are treeified, split, or untreeified, we keep
     * them in the same relative access/traversal order (i.e., field
     * Node.next) to better preserve locality, and to slightly
     * simplify handling of splits and traversals that invoke
     * iterator.remove. When using comparators on insertion, to keep a
     * total ordering (or as close as is required here) across
     * rebalancings, we compare classes and identityHashCodes as
     * tie-breakers.
     *
     * The use and transitions among plain vs tree modes is
     * complicated by the existence of subclass LinkedHashMap. See
     * below for hook methods defined to be invoked upon insertion,
     * removal and access that allow LinkedHashMap internals to
     * otherwise remain independent of these mechanics. (This also
     * requires that a map instance be passed to some utility methods
     * that may create new nodes.)
     *
     * The concurrent-programming-like SSA-based coding style helps
     * avoid aliasing errors amid all of the twisty pointer operations.
     */

大致理解一下 主要意思大致是:

第一点:红黑树的节点占得空间 大致是普通节点的两倍  能用普通节点还是用普通节点 但是只有当节点数量过大 而且链表上挂的节点过多时 采用红黑树来代替链表结构 这个红黑树 只是为了你查找时快速解决hash冲突的。

举例说明 数组中某一链表上挂了8个节点 此时get操作 再链表中找到其中某节点的效率大约是n/2 查找4次因为要依次遍历 用equals方法

但是如果此时 变为红黑树 查找的时间效率就变成了 logn也就是查找3次  

典型的用空间换时间   达成平衡

而至于树化的节点数目为什么设置在8  那是因为人家通过计算得出 随机的hash函数发生hash冲突是符合泊松分布的

也就是说 即使是随机的hash函数  发生hash冲突 让链表长度达到8的可能也很小很小了 原文概率:8: 0.00000006

那是不是只要有链表长度达到8就进行树化呢 我们来看代码。依然是截取putval中的一段代码:在遍历数组是检查每一条链表的长度 如果长度超过8 则调用treeifyBin方法 

final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
//如果原数组是null或者数组中元素个数小于64 依然采取resize方法
        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);
        }
    }

 对,没有看错。当检测到一条链表长度为8的时候,并没有树化,这个hashmap直接扩容。通过扩容的方式 将一条链表打散开来。因此 hahsmap的树化必须满足两个条件 总的元素数量>=64 一条链表上元素数量至少>=8

至此第二个问题解决

开始讲述第三个问题:jdk1.7的头插有什么问题  jdk1.8做出了什么相应的改变

众所周知:hashmap的扩容是先创建了一个二倍的空间 再把旧的hashmap元素 转移到新hashmap上

我们先来看下1.7版本的扩容和转移

/**
     * JDK1.7  用的头插法 所谓头插:第一个加入table[index]的元素  在其他元素加入到该链表中来的时候 不断下沉 只能排在链表尾部
     * @param newCapacity
     */
    void resize(int newCapacity) {   //传入新的容量
        Entry[] oldTable = table;    //引用扩容前的Entry数组
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {  //扩容前的数组大小如果已经达到最大(2^30)了
            threshold = Integer.MAX_VALUE; //修改阈值为int的最大值(2^31-1),这样以后就不会扩容了
            return;
        }

        Entry[] newTable = new Entry[newCapacity];  //初始化一个新的Entry数组
        transfer(newTable);                         //!!将数据转移到新的Entry数组里
        table = newTable;                           //HashMap的table属性引用新的Entry数组
        threshold = (int) (newCapacity * loadFactor);//修改阈值
    }
 /**
     * 旧的数组 转换到新数组的数据转移方法
     * @param newTable
     */
    void transfer(Entry[] newTable) {
        Entry[] src = table;
        int newCapacity = newTable.length;
        //在数组上 做一层循环
        for (int j = 0; j < src.length; j++) {
            Entry<K, V> e = src[j];
            //拿到每条链表的头结点 并且释放src数组空间
            if (e != null) {
                src[j] = null;
                /**
                 * 先用next标记 头结点e的下一个节点  然后计算头结点在新数组中的新下标位置 index
                 * 如果新数组的index位置已经有元素 则这个元素下沉 作为e节点的下一节点 e放入index 并作为链表的头结点(头插法)
                 * 然后e指针指向next 依次遍历链表元素
                 */
                do {
                    Entry<K, V> next = e.next;
                    int i = indexFor(e.hash, newCapacity);
                    e.next = newTable[i];
                    newTable[i] = e;
                    e = next;
                } while (e != null);
            }
        }
    }

里面注释写的已经很清楚了 就是循环数组 依次遍历链表元素 重新hash 新元素不断放在数组作为链表头 下面接之前该位置的链表。  那么头插法 为什么会出现问题呢。

 我们思考一种情况:hashmap初始容量是2    分别是 数组单元1 数组单元2  此时数组单元1中放的是a.next=b的链表 单元2为null。

此时两个线程同时来putval  x线程先来 执行扩容和  transfer  e指向a next指向b 此时线程1的时间片刚好用完

线程2来执行扩容和transfer  先把a放到了扩容后的某位置 假设放b的时候 hash冲突 b也要放到a所在的数组单元 所以此时 b放在该位置 b.next = a  ;线程2执行完毕

线程1接着回来执行:先把a节点放在了 新数组的某位置 然后 e指向了了原数组的b  next = e.next =b.next 看下线程1的引用 =a

形成了循环 就会变成同一个数组单元里 b->a->b    在get的是时候就会出现一直循环导致cpu占用过高的情况。

如果我没说很清楚的话 请暂时移步疫苗:Java HashMap的死循环 | 酷 壳 - CoolShell看一下 这里有图解。

总结一下 就是hashmap的头插法问题是由多线程导致的。而且注意1.7中是先进行扩容,然后再转移,最后插入当前要putval的值

每次resize之后插入节点 都是要重新计算hash。

说完了1.7 我们再来学习下1.8的代码

先提出个问题    如果不rehash   有什么办法能将之前很长的链表平均分开吗  

有!扩容两倍的同时 把某位置的链表大致分到原位置 和原位置+扩容空间

比如原数组大小 8     数组位a[3]的链表    根据hash值分散到新数组中a[3] 和 a[11]的位置  3位低位  11为高位

  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 { // 按照e.hash & oldcap运算 等于0的放在原位置 等于1的放在原位置+扩容容量   其中lowhead 用来记录链表头 lowtail用来记录链表尾 尾插 high也一样 不多赘述
                        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;

注意  hashmap1.8中 是先put新节点 再判断是否超出扩容容量  再一块进行转移。

至此 第三个问题回答完毕

第四个问题比较简单 当做一个小插曲就好:

为什么重写了一个hash方法 不直接 用hashcode   原因 int 32位  把高低16位的特征混合  


    /**
     * hash方法 对key的高低16位进行特征混合 原因:(n-1)&key.hash   高区的16位很有可能会被数组槽位数的二进制码所屏蔽  比如n=16 hash只有低四位有效
     * 那么 如果两个key的hash值 刚好只有低四位相同 例如  10011100 和01101100 只考虑到低4位 明显会发生hash冲突 但是如果1001^1100=0101
     * (为表述简答,只用8位数据举例)                                                                           0110^1100=1010
     *                                                                                                        刚好区分开hash值
     * @param key
     * @return
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

 最后一个问题 来详细看一下resize和putval的完整代码

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

 因此扩容的具体步骤是:

1.检测 是否超出最大容量 容量扩大两倍  扩容容量(shreshold)扩大为2倍

2.如果之前只是初始了hashmap的相关参数 未放入元素 则初始化容量等等 计算扩容容量

3.依次循环遍历 用尾插法 向新的hashmap中转移数据

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //hashmap放入第一个值时,进行的第一次初始化
        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;
            //否则和当前元素比较hash值和key值 都相同 就更新value
            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 {//如果当前位置有元素 且该元素 的key 不等于要插入的元素  循环遍历 检测链表长度
                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;
                    }//key相同就更新
                    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;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值