/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
*/transientNode<K,V>[] table;// Node数组声明
总结,根据 hash & oldCap 最高位是否为0,来将旧链表拆分成为两个链表,然后分别放到新table中的第j 和 第 j + oldCap 位置。the elements from each bin must either stay at same index, or move with a power of two offset in the new table.
红黑树的调整??
代码注释:
/**
* 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
*/finalNode<K,V>[]resize(){Node<K,V>[] oldTab = table;int oldCap =(oldTab ==null)?0: oldTab.length;int oldThr = threshold;int newCap, newThr =0;// 根据oldCap,oldThr 计算 newCap,newThr。if(oldCap >0){if(oldCap >= MAXIMUM_CAPACITY){
threshold =Integer.MAX_VALUE;return oldTab;}elseif((newCap = oldCap <<1)< MAXIMUM_CAPACITY &&// table 的 capacity 扩容一倍
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr <<1;// double threshold 扩容一倍}elseif(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;// 完成cap、threshold更新过程,开始扩容@SuppressWarnings({"rawtypes","unchecked"})Node<K,V>[] newTab =(Node<K,V>[])newNode[newCap];// new 一个新的table数组
table = newTab;if(oldTab !=null){// 当前map不为空,需要处理旧的table,更新到 newTab中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;// 只有一个元素elseif(e instanceofTreeNode)((TreeNode<K,V>)e).split(this, newTab, j, oldCap);// 红黑树拆分else{// preserve orderNode<K,V> loHead =null, loTail =null;// low head, low Tail。 低位链表的头尾Node<K,V> hiHead =null, hiTail =null;// hight head, hight Tail。 高位链表的头尾Node<K,V> next;do{
next = e.next;// oldCap的二进制最高位为1,其余位置为0.根据hash值最高位是否为0,将一个链表拆分成为两个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;// 赋值到 j 位置}if(hiTail !=null){
hiTail.next =null;
newTab[j + oldCap]= hiHead;// 赋值到 j+ oldCap}}}}}return newTab;}