HashMap实现原理及源码分析(jdk1.8)

HashMap底层由数组+链表+红黑树组成,可接受null值,非线程安全node

  • 一、基本属性
 
 
transient Node<K,V>[] table; //hashmap数组
 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认容量16

    static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量

    static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认负载因子

    static final int TREEIFY_THRESHOLD = 8; //链表节点转换红黑树节点的阈值

    static final int UNTREEIFY_THRESHOLD = 6; //红黑树节点转换链表节点的阈值

    static final int MIN_TREEIFY_CAPACITY = 64;// 转红黑树时, table的最小长度 // 基本hash节点, 继承自Entry
    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; } } //构造函数
    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); } //构造函数
    public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } //构造函数
    public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; } // 红黑树节点
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } /** * Returns root of tree containing this node. */
        final TreeNode<K,V> root() { for (TreeNode<K,V> r = this, p;;) { if ((p = r.parent) == null) return r; r = p; } } //...
    }
  • 二、hash算法

HashMap定位数组索引位置,直接决定了hash方法的离散性能。下面是定位哈希桶数组的源码:算法

static final int hash(Object key) { // 计算key的hash值
        int h; // 1.先拿到key的hashCode值; 2.将hashCode的高16位参与运算
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } // 将(tab.length - 1) 与 hash值进行&运算
    int index = (tab.length - 1) & hash;

HashMap底层数组的长度老是2的n次方,而且取模运算为“h mod table.length”,对应上面的公式,能够获得该运算等同于“h & (table.length - 1)”。这是HashMap在速度上的优化,由于&比%具备更高的效率。数组

在JDK1.8的实现中,还优化了高位运算的算法,将hashCode的高16位与hashCode进行异或运算,主要是为了在table的length较小的时候,让高位也参与运算,而且不会有太大的开销。安全

  • 三、get方法
final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; // table不为空 && table长度大于0 && table索引位置(根据hash值计算出)节点不为空
        if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { // first的key等于传入的key则返回first对象
            if (first.hash == hash && // always check first node
                    ((k = first.key) == key || (key != null && key.equals(k)))) return first; //first的key不等于传入的key则说明是链表,向下遍历
            if ((e = first.next) != null) { // 判断是否为TreeNode,是则为红黑树 // 若是是红黑树节点,则调用红黑树的查找目标节点方法getTreeNode
                if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); //走下列步骤表示是链表,循环至节点的key与传入的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方法
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; // table是否为空或者length等于0, 若是是则调用resize方法进行初始化
        if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 经过hash值计算索引位置, 若是table表该索引位置节点为空则新增一个
        if ((p = tab[i = (n - 1) & hash]) == null) // 将索引位置的头节点赋值给p
            tab[i] = newNode(hash, key, value, null); // table表该索引位置不为空
        else { //判断p节点的hash值和key值是否跟传入的hash值和key值相等
            Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; // 若是相等, 则p节点即为要查找的目标节点,赋值给e // 判断p节点是否为TreeNode, 若是是则调用红黑树的putTreeVal方法查找目标节点
            else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); // 走到这表明p节点为普通链表节点
            else { // 遍历此链表, binCount用于统计节点数
                for (int binCount = 0; ; ++binCount) { //p.next为空表明目标节点不存在
                    if ((e = p.next) == null) { //新增一个节点插入链表尾部
                        p.next = newNode(hash, key, value, null); //若是节点数目超过8个,调用treeifyBin方法将该链表转换为红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
 treeifyBin(tab, hash); break; } //e节点的hash值和key值都与传入的相等, 则e即为目标节点,跳出循环
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } // e不为空则表明根据传入的hash值和key值查找到了节点,将该节点的value覆盖,返回oldValue
            if (e != null) { // existing mapping for key
                V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); // 用于LinkedHashMap
                return oldValue; } } //map修改次数加1
        ++modCount; //map节点数加1,若是超过阀值,则扩容
        if (++size > threshold) resize(); afterNodeInsertion(evict); // 用于LinkedHashMap
        return null; }

从上面的源码分析能够看出数据结构

一、若是节点已经存在,则更新原值app

二、若是节点不存在,则插入数组中,若是数组已经有值,则判断是非是红黑树,若是是,则调用红黑树方法插入函数

三、若是插入的是链表,插入尾部,而后判断节点数是否超过8,若是超过,则转换为红黑树源码分析

四、先插入的数据,后面判断是否超过阀值再进行的扩容性能

 

putTreeVal,插入红黑树方法就不看了,看下treeifyBin方法,该方法是将链表转化为红黑树,优化

final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; // table为空或者table的长度小于64, 进行扩容
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); // 根据hash值计算索引值, 遍历该索引位置的链表
    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)    // tl为空表明为第一次循环
                hd = p; // 头结点
            else { p.prev = tl;    // 当前节点的prev属性设为上一个节点
                tl.next = p;    // 上一个节点的next属性设置为当前节点
 } tl = p; // tl赋值为p, 在下一次循环中做为上一个节点
        } while ((e = e.next) != null);    // e指向下一个节点 // 将table该索引位置赋值为新转的TreeNode的头节点
        if ((tab[index] = hd) != null) hd.treeify(tab); // 以头结点为根结点, 构建红黑树
    }
}

能够看到,会先判断tab的节点数是否超过64,若是没超过,则进行扩容,若是超过了才会转换为红黑树

能够获得两个结论

一、何时转换为红黑树

当链表数目超过8,而且map节点数量超过64,才会转换为红黑树

二、何时扩容(前提是map数目没有超过最大容量值  1<<30 )

新增节点时,发生了碰撞,而且节点数目超过阀值

新增节点时,发生了碰撞,节点数量木有超过阀值,可是链表数目>8,map节点<64时

 

再看下resize()方法

final Node<K,V>[] resize() { //oldTab保存未扩容的tab
        Node<K,V>[] oldTab = table; //oldTab最大容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length; //oldTab阀值
        int oldThr = threshold; int newCap, newThr = 0; //若是老map有值
        if (oldCap > 0) { // 老table的容量超过最大容量值,设置阈值为Integer.MAX_VALUE,返回老表
            if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; //老table的容量没有超过最大容量值,将新容量赋值为老容量*2,若是新容量<最大容量而且老容量>=16, 则将新阈值设置为原来的两倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold
 } else if (oldThr > 0) // 老表的容量为0, 老表的阈值大于0, 是由于初始容量被放入阈值
            newCap = oldThr;    // 则将新表的容量设置为老表的阈值
        else {   //老表的容量为0, 老表的阈值为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) { // 将索引值为j的老表头节点赋值给e
                    oldTab[j] = null; //将老表的节点设置为空, 以便垃圾收集器回收空间 // 若是e.next为空, 则表明老表的该位置只有1个节点, // 经过hash值计算新表的索引位置, 直接将该节点放在该位置
                    if (e.next == null) //                         newTab[e.hash & (newCap - 1)] = e; //e.next不为空,判断是不是红黑树
                    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; //若是e的hash值与老表的容量进行与运算为0,则扩容后的索引位置跟老表的索引位置同样
                            if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } //若是e的hash值与老表的容量进行与运算为1,则扩容后的索引位置为:老表的索引位置+oldCap
                            else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; // 最后一个节点的next设为空
                            newTab[j] = loHead; // 将原索引位置的节点设置为对应的头结点
 } if (hiTail != null) { hiTail.next = null; // 最后一个节点的next设为空
                            newTab[j + oldCap] = hiHead; // 将索引位置为原索引+oldCap的节点设置为对应的头结点
 } } } } } return newTab; }

能够看出,扩容时,节点重hash只分布在原索引位置与原索引+oldCap位置,为何呢

假设老表的容量为16,即oldCap=16,则新表容量为16*2=32,假设节点1的hash值为0000 0000 0000 0000 0000 1111 0000 1010,节点2的hash值为0000 0000 0000 0000 0000 1111 0001 1010,则节点1和节点2在老表的索引位置计算以下图计算1,因为老表的长度限制,节点1和节点2的索引位置只取决于节点hash值的最后4位。再看计算2,计算2为新表的索引计算,能够知道若是两个节点在老表的索引位置相同,则新表的索引位置只取决于节点hash值倒数第5位的值,而此位置的值恰好为老表的容量值16,此时节点在新表的索引位置只有两种状况:原索引位置和原索引+oldCap位置(在此例中即为10和10+16=26)。因为结果只取决于节点hash值的倒数第5位,而此位置的值恰好为老表的容量值16,所以此时新表的索引位置的计算能够替换为计算3,直接使用节点的hash值与老表的容量16进行位于运算,若是结果为0则该节点在新表的索引位置为原索引位置,不然该节点在新表的索引位置为原索引+oldCap位置。

 

  • 五、remove()方法
public V remove(Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value; } final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node<K,V>[] tab; Node<K,V> p; int n, index; // 若是table不为空而且根据hash值计算出来的索引位置不为空, 将该位置的节点赋值给p
    if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { Node<K,V> node = null, e; K k; V v; // 若是p的hash值和key都与入参的相同, 则p即为目标节点, 赋值给node
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p; else if ((e = p.next) != null) {    // 不然向下遍历节点
            if (p instanceof TreeNode)  // 若是p是TreeNode则调用红黑树的方法查找节点
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key); else { do {    // 遍历链表查找符合条件的节点 // 当节点的hash值和key与传入的相同,则该节点即为目标节点
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e;    // 赋值给node, 并跳出循环
                        break; } p = e;  // p节点赋值为本次结束的e
                } while ((e = e.next) != null); // 指向像一个节点
 } } // 若是node不为空(即根据传入key和hash值查找到目标节点),则进行移除操做
        if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { if (node instanceof TreeNode)   // 若是是TreeNode则调用红黑树的移除方法
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable); // 走到这表明节点是普通链表节点 // 若是node是该索引位置的头结点则直接将该索引位置的值赋值为node的next节点
            else if (node == p) tab[index] = node.next; // 不然将node的上一个节点的next属性设置为node的next节点, // 即将node节点移除, 将node的上下节点进行关联(链表的移除) 
            else p.next = node.next; ++modCount; // 修改次数+1
            --size; // table的总节点数-1
            afterNodeRemoval(node); // 供LinkedHashMap使用
            return node;    // 返回被移除的节点
 } } return null; }

 

  • 六、JDK1.7和1.8的区别

一、JDK1.7的时候使用的是数组+ 单链表的数据结构。可是在JDK1.8及以后时,使用的是数组+链表+红黑树的数据结构(当链表的深度达到8的时候,也就是默认阈值,就会自动扩容把链表转成红黑树的数据结构来把时间复杂度从O(n)变成O(logN)提升了效率)

二、JDK1.7用的是头插法,而JDK1.8及以后使用的都是尾插法,那么他们为何要这样作呢?由于JDK1.7是用单链表进行的纵向延伸,当采用头插法时会容易出现逆序且环形链表死循环问题。可是在JDK1.8以后是由于加入了红黑树使用尾插法,可以避免出现逆序且链表死循环的问题。

三、扩容后数据存储位置的计算方式也不同:1. 在JDK1.7的时候是直接用hash值和须要扩容的二进制数进行&(这里就是为何扩容的时候为啥必定必须是2的多少次幂的缘由所在,由于若是只有2的n次幂的状况时最后一位二进制数才必定是1,这样能最大程度减小hash碰撞)(hash值 & length-1),而在JDK1.8的时候直接用了JDK1.7的时候计算的规律,也就是扩容前的原始位置+扩容的大小值=JDK1.8的计算方式,而再也不是JDK1.7的那种异或的方法。可是这种方式就至关于只须要判断Hash值的新增参与运算的位是0仍是1就直接迅速计算出了扩容后的储存方式。

四、jdk1.7 先扩容再put ,jdk1.8 先put再扩容

 

参考:http://www.javashuo.com/article/p-eyugcawb-ch.html

相关文章
相关标签/搜索