天天看点

一篇文章解读JDK1.8 HashMap源码

一篇文章解读JDK1.8 HashMap源码

    • 第一次写博客
    • 什么是HashMap?
    • HashMap的4个构造方法
    • Hash值数组下标的计算
    • HashMap初始化容量/扩容resize
    • put操作
    • get操作
    • 桶的树形化 treeifyBin()
      • 红黑树中添加元素 putTreeVal()
      • 红黑树中查找元素 getTreeNode()
      • 树形结构修剪 split()
    • 总结

第一次写博客

最近在学习HashMap相关的知识,想总结一下以固化对这个知识点的认识,第一次写博客,如果写的不好,请大家多多指教。

什么是HashMap?

HashMap是顶层使用哈希表(数组+链表),当链表长度过长时会将链表转为红黑树以实现Olog(n)查询时间复杂度

HashMap的4个构造方法

//创建一个空的哈希表,初始容量为 16,加载因子为 0.75
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//创建一个空的哈希表,指定容量,使用默认的加载因子
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//创建一个空的哈希表,指定容量和加载因子
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);
}

//创建一个内容为参数 m 的内容的哈希表
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}
/**
 * Returns a power of two size for the given target capacity.
 */
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;
}
/**
 * Implements Map.putAll and Map constructor
 *
 * @param m the map
 * @param evict false when initially constructing this map, else
 * true (relayed to method afterNodeInsertion).
 */
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
        	//计算需要在HashMap中分配多少容量
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
        	//如果Map的长度大于HashMap原来的容量,则给HashMap扩容
            resize();
            //遍历Map,给Map中的key值计算放入到HashMap中的数组下标,将<Key,Value>放入到HashMap中
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}
           
1.第一个构造方法中,将加载因子设为默认的加载因子0.75。
2.第二个构造方法,传入一个初始化容量,然后将初始化容量和默认的加载因子调用了第三个构造方法。
3.第三个构造方法,传入一个initialCapacity和loadFactor,当initialCapacity大于最大限制容量时,会将容量设为最大容量,将loadFactor赋值给加载因子,在tableSizeFor方法中会将容量转为最接近目标容量的2的次幂的数值,由此看出HashMap的容量必须是2的次幂,如果不是2的次幂会自动转成目标容量最接近的2的次幂。
4.第四个构造方法是将一个实现了Map接口的对象传入,首先将加载因子设置为默认的0.75,然后将Map放入到HashMap中。
           

Hash值数组下标的计算

/**
 - 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);
 }
           
一篇文章解读JDK1.8 HashMap源码
  • 高 16bit 不变,低 16bit 和高 16bit 做了一个异或
  • (n - 1) & hash --> 得到下标,n的值是HashMap的容量,例如上图容量是16,n-1得到15 即1111

HashMap初始化容量/扩容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;
    //如果旧容量大于0
    if (oldCap > 0) {
    	//已经达到最大容量,不能再扩容
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //如果旧容量的2倍小于最大容量且旧容量大于等于默认容量16,则将容量扩为旧容量的两倍
        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
    	//如果旧容量和旧阈值都为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)
                	//将原来的下标和新的容量减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;
}
           

扩容需要记住的几点:

  • 初始化扩容时,容量为默认的容量,阈值为容量*加载因子
  • 对已有hash表扩容时,容量和阈值为原来容量的两倍
  • 如果原来桶中的元素结构是树形结构,则要将新数组中该桶的元素也变为树形结构
  • 对已有数据的hash表扩容时,需要对已有元素进行rehash的操作,计算新的数组下标,rehash算法是 e.hash&(newCap-1)

put操作

public V put(K key, V value) { 
//先调用 hash() 方法计算位置 
return putVal(hash(key), key, value, false, true); 
}
/**
 * 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))))
            //p 指向要插入的桶第一个元素的位置,如果p的哈希值、键、值和要添加的一样,就停止找,e 指向 p
            e = p;
        //如果不一样且桶中元素是树状结构,则调用putTreeVal方法插入元素
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
        	//否则用传统方法插入到链表
        	//遍历链表
            for (int binCount = 0; ; ++binCount) {
            	//如果p后面没有元素了,则将元素链到尾部
                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;
            }
        }
        //找到了key对应的键值对所处的位置
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
            	//覆盖原来的Value值
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    //超过了阈值执行扩容操作
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
           

根据代码可以总结插入逻辑如下:

  1. 先调用 hash()方法进行计算哈希值
  2. 然后调用 putVal()方法根据哈希值进行相关操作
  3. 如果当前哈希表内容为空,新建一个哈希表
  4. 如果要插入的桶中没有元素,新建个节点放进去
  5. 否则从桶中第一个元素开始查找哈希值对应位置

    1.如果桶中第一个元素的哈希值要和添加的一样,替换,结束查找

    2.如果第一个元素不一样,而且当前采用的还是 JDK8以后的树形节点,调用 putTreeVal()进行插入

    3.否则还是从传统的链表数据中查找、替换、结束查找

    4.当这个桶内链表个数大于等于 8 ,就要调用 treeifyBin方法进行树形化

最后检查是否需要扩容

思考:

为什么从链表转为红黑树的阈值是8?从红黑树解除为链表的阈值是6?而不是其它数值?而不是直接将链表替换成红黑树?
           

因为Map中桶的元素初始化是链表保存的,其查找性能是O(n),而树结构能将查找性能提升到O(log(n))。当链表长度很小的时候,即使遍历,速度也非常快,但是当链表长度不断变长,肯定会对查询性能有一定的影响,所以才需要转成树。

get操作

首先计算key的hash值,然后调用getNode方法返回键值对的value值

public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
 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) {
         //判断第一个元素值和key值是否相等
         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. 计算key值hash值
  2. 利用hash&(n-1)算法找到桶在数组的位置
  3. 遍历桶中的链表找到元素

桶的树形化 treeifyBin()

在JDK1.8表,为了提供查询效率,当桶中的链表元素个数超过TREEIFY_THRESHOLD(默认是 8 )的时候,会将链表转化为红黑树的结构存在,以满足对查询性能的提升。

其中将桶元素树形化的方法就是treeifyBin()

/**
  * Replaces all linked nodes in bin at index for given hash unless
  * table is too small, in which case resizes instead.
  */
 final void treeifyBin(Node<K,V>[] tab, int hash) {
     int n, index; Node<K,V> e;
     //如果哈希表是空或者数组元素长度小于树形化阈值(默认是64)则去扩容
     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);
         //将新的树结点链表赋给第index个桶
         if ((tab[index] = hd) != null)
         	//将二叉树转换成红黑树
             hd.treeify(tab);
     }
 }
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);
        }
        final void treeify(Node<K,V>[] tab) {//将链表转换成红黑树
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {//遍历链表中的每一个TreeNode,当前结点为x
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                if (root == null) {         //对于第一个树结点,当前红黑树的root == null,所以第一个结点是树的根,设置为黑色
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else { //对于余下的结点:
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root; ; ) {//从根结点开始遍历,寻找当前结点x的插入位置
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)   //如果当前结点的hash值小于根结点的hash值,方向dir = -1;
                            dir = -1;
                        else if (ph < h)                //如果当前结点的hash值大于根结点的hash值,方向dir = 1;
                            dir = 1;
                        else if ((kc == null &&         //如果x结点的key没有实现comparable接口,或者其key和根结点的key相等(k.compareTo(x) == 0)仲裁插入规则
                                  (kc = comparableClassFor(k)) == null) ||      //只有k的类型K直接实现了Comparable<K>接口,才返回K的class,否则返回null,间接实现也不行。
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);         //仲裁插入规则

                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {      //如果p的左右结点都不为null,继续for循环,否则执行插入
                            x.parent = xp;
                            if (dir <= 0)           //dir <= 0,插入到左儿子
                                xp.left = x;
                            else            //否则插入到右结点
                                xp.right = x;
                            root = balanceInsertion(root, x);   //插入后进行树的调整,使之符合红黑树的性质
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);         //Ensures that the given root is the first node of its bin.
        }
}

	/**
	  * Tie-breaking utility for ordering insertions when equal
	  * hashCodes and non-comparable. We don't require a total
	  * order, just a consistent insertion rule to maintain
	  * equivalence across rebalancings. Tie-breaking further than
	  * necessary simplifies testing a bit.
	  */
	static int tieBreakOrder(Object a, Object b) {
	  int d;
	  if (a == null || b == null ||
	      (d = a.getClass().getName().
	       compareTo(b.getClass().getName())) == 0)
	    d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
	         -1 : 1);
	  return d;
	}
}
           

上述操作做了这些事:

根据哈希表中元素个数确定是扩容还是树形化

如果是树形化

1.遍历桶中的元素,创建相同个数的树形节点,复制内容,建立起联系

2.然后让桶第一个元素指向新建的树头结点,替换桶的链表内容为树形内容

但是我们发现,之前的操作并没有设置红黑树的颜色值,现在得到的只能算是个二叉树。在 最后调用树形节点 hd.treeify(tab) 方法进行塑造红黑树。

红黑树中添加元素 putTreeVal()

final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                               int h, K k, V v) {
    Class<?> kc = null;
    boolean searched = false;
    TreeNode<K,V> root = (parent != null) ? root() : this;
    //每次添加元素时,从根节点遍历,对比哈希值
    for (TreeNode<K,V> p = root;;) {
        int dir, ph; K pk;
        if ((ph = p.hash) > h)
            dir = -1;
        else if (ph < h)
            dir = 1;
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))  
        //如果当前节点的哈希值、键和要添加的都一致,就返回当前节点(奇怪,不对比值吗?)
            return p;
        else if ((kc == null &&
                  (kc = comparableClassFor(k)) == null) ||
                 (dir = compareComparables(kc, k, pk)) == 0) {
            //如果当前节点和要添加的节点哈希值相等,但是两个节点的键不是一个类,只好去挨个对比左右孩子 
            if (!searched) {
                TreeNode<K,V> q, ch;
                searched = true;
                if (((ch = p.left) != null &&
                     (q = ch.find(h, k, kc)) != null) ||
                    ((ch = p.right) != null &&
                     (q = ch.find(h, k, kc)) != null))
                    //如果从 ch 所在子树中可以找到要添加的节点,就直接返回
                    return q;
            }
            //哈希值相等,但键无法比较,只好通过特殊的方法给个结果
            dir = tieBreakOrder(k, pk);
        }

        //经过前面的计算,得到了当前节点和要插入节点的一个大小关系
        //要插入的节点比当前节点小就插到左子树,大就插到右子树
        TreeNode<K,V> xp = p;
     //这里有个判断,如果当前节点还没有左孩子或者右孩子时才能插入,否则就进入下一轮循环 
        if ((p = (dir <= 0) ? p.left : p.right) == null) {
            Node<K,V> xpn = xp.next;
            TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
            if (dir <= 0)
                xp.left = x;
            else
                xp.right = x;
            xp.next = x;
            x.parent = x.prev = xp;
            if (xpn != null)
                ((TreeNode<K,V>)xpn).prev = x;
            //红黑树中,插入元素后必要的平衡调整操作
            moveRootToFront(tab, balanceInsertion(root, x));
            return null;
        }
    }
}

//这个方法用于 a 和 b 哈希值相同但是无法比较时,直接根据两个引用的地址进行比较
//这里源码注释也说了,这个树里不要求完全有序,只要插入时使用相同的规则保持平衡即可
 static int tieBreakOrder(Object a, Object b) {
    int d;
    if (a == null || b == null ||
        (d = a.getClass().getName().
         compareTo(b.getClass().getName())) == 0)
        d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
             -1 : 1);
    return d;
}
           

通过上面的代码可以知道,HashMap 中往红黑树中添加一个新节点 n 时,有以下操作:

  1. 从根节点开始遍历当前红黑树中的元素 p,对比 n 和 p 的哈希值;
  2. 如果哈希值相等并且键也相等,就判断为已经有这个元素(这里不清楚为什么不对比值);
  3. 如果哈希值就通过其他信息,比如引用地址来给个大概比较结果,这里可以看到红黑树的比较并不是很准确,注释里也说了,只是保证个相对平衡即可;
  4. 最后得到哈希值比较结果后,如果当前节点 p 还没有左孩子或者右孩子时才能插入,否则就进入下一轮循环;
  5. 插入元素后还需要进行红黑树例行的平衡调整,还有确保根节点的领先地位。

红黑树中查找元素 getTreeNode()

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

树形结构修剪 split()

HashMap 中, resize() 方法的作用就是初始化或者扩容哈希表。当扩容时,如果当前桶中元素结构是红黑树,并且元素个数小于链表还原阈值 UNTREEIFY_THRESHOLD (默认为 6),就会把桶中的树形结构缩小或者直接还原(切分)为链表结构,调用的就是 split():

//参数介绍
//tab 表示保存桶头结点的哈希表
//index 表示从哪个位置开始修剪
//bit 要修剪的位数(哈希值)
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
    TreeNode<K,V> b = this;
    // Relink into lo and hi lists, preserving order
    TreeNode<K,V> loHead = null, loTail = null;
    TreeNode<K,V> hiHead = null, hiTail = null;
    int lc = 0, hc = 0;
    for (TreeNode<K,V> e = b, next; e != null; e = next) {
        next = (TreeNode<K,V>)e.next;
        e.next = null;
        //如果当前节点哈希值的最后一位等于要修剪的 bit 值
        if ((e.hash & bit) == 0) {
                //就把当前节点放到 lXXX 树中
            if ((e.prev = loTail) == null)
                loHead = e;
            else
                loTail.next = e;
            //然后 loTail 记录 e
            loTail = e;
            //记录 lXXX 树的节点数量
            ++lc;
        }
        else {  //如果当前节点哈希值最后一位不是要修剪的
                //就把当前节点放到 hXXX 树中
            if ((e.prev = hiTail) == null)
                hiHead = e;
            else
                hiTail.next = e;
            hiTail = e;
            //记录 hXXX 树的节点数量
            ++hc;
        }
    }


    if (loHead != null) {
        //如果 lXXX 树的数量小于 6,就把 lXXX 树的枝枝叶叶都置为空,变成一个单节点
        //然后让这个桶中,要还原索引位置开始往后的结点都变成还原成链表的 lXXX 节点
        //这一段元素以后就是一个链表结构
        if (lc <= UNTREEIFY_THRESHOLD)
            tab[index] = loHead.untreeify(map);
        else {
        //否则让索引位置的结点指向 lXXX 树,这个树被修剪过,元素少了
            tab[index] = loHead;
            if (hiHead != null) // (else is already treeified)
                loHead.treeify(tab);
        }
    }
    if (hiHead != null) {
        //同理,让 指定位置 index + bit 之后的元素
        //指向 hXXX 还原成链表或者修剪过的树
        if (hc <= UNTREEIFY_THRESHOLD)
            tab[index + bit] = hiHead.untreeify(map);
        else {
            tab[index + bit] = hiHead;
            if (loHead != null)
                hiHead.treeify(tab);
        }
    }
}
           

从上述代码可以看到,HashMap 扩容时对红黑树节点的修剪主要分两部分,先分类、再根据元素个数决定是还原成链表还是精简一下元素仍保留红黑树结构。

1.分类

指定位置、指定范围,让指定位置中的元素 (hash & bit) == 0 的,放到 lXXX 树中,不相等的放到 hXXX 树中。

2.根据元素个数决定处理情况

符合要求的元素(即 lXXX 树),在元素个数小于 6 时还原成链表,最后让哈希表中修剪的痛 tab[index] 指向 lXXX 树;在元素个数大于 6 时,还是用红黑树,只不过是修剪了下枝叶;

不符合要求的元素(即 hXXX 树)也是一样的操作,只不过最后它是放在了修剪范围外 tab[index + bit]。

总结

JDK 1.8 以后哈希表的 添加、删除、查找、扩容方法都增加了一种 节点为 TreeNode 的情况:

添加时,当桶中链表个数超过 8 时会转换成红黑树;
删除、扩容时,如果桶中结构为红黑树,并且树中元素个数太少的话,会进行修剪或者直接还原成链表结构;
查找时即使哈希函数不优,大量元素集中在一个桶中,由于有红黑树结构,性能也不会差。

1.HashMap 的缺点:不同步
当多线程并发访问一个 哈希表时,需要在外部进行同步操作,否则会引发数据不同步问题。
你可以选择加锁,也可以考虑用 ConcurrentHashMap,变成个线程安全的 Map:

2.HashMap 三个视图返回的迭代器都是 fail-fast 的:如果在迭代时使用非迭代器方法修改了 map 的内容、结构,迭代器就会报 ConcurrentModificationException 的错。

3.当 HashMap 中有大量的元素都存放到同一个桶中时,这时候哈希表里只有一个桶,这个桶下有一条长长的链表,这个时候 HashMap 就相当于一个单链表,假如单链表有 n 个元素,遍历的时间复杂度就是 O(n),完全失去了它的优势。

针对这种情况,JDK 1.8 中引用了 红黑树(时间复杂度为 O(logn)) 优化这个问题。

4.HashMap 允许 key, value 为 null,同时他们都保存在第一个桶中。

5.HashMap 中 equals() 和 hashCode() 有什么作用?

HashMap 的添加、获取时需要通过 key 的 hashCode() 进行 hash(),然后计算下标 ( n-1 & hash),从而获得要找的同的位置。

当发生冲突(碰撞)时,利用 key.equals() 方法去链表或树中去查找对应的节点。
           

继续阅读