putVal() 方法解析
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为空,则进行必要字段的初始化 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 获取长度(16) // 如果根据hash值获取的结点为空,则新建一个结点 if ((p = tab[i = (n - 1) & hash]) == null) // 此处 & 代替了 % (除法散列法进行散列) tab[i] = newNode(hash, key, value, null); // 这里的p结点是根据hash值算出来对应在数组中的元素 else { Node<K,V> e; K k; // 如果新插入的结点和table中p结点的hash值,key值相同的话 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); // 链表长度大于8时,将链表转红黑树 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 p = e; } } // 如果存在这个映射就覆盖 if (e != null) { // existing mapping for key V oldValue = e.value; // 判断是否允许覆盖,并且value是否为空 if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); // 回调以允许LinkedHashMap后置操作 return oldValue; } } ++modCount; // 更改操作次数 if (++size > threshold) // 大于临界值 // 将数组大小设置为原来的2倍,并将原先的数组中的元素放到新数组中 // 因为有链表,红黑树之类,因此还要调整他们 resize(); // 回调以允许LinkedHashMap后置操作 afterNodeInsertion(evict); return null; }resize()解析:
//初始化或者扩容之后元素调整 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) { // 如果原table不为空 // 如果数组长度达到最大值,则修改临界值为Integer.MAX_VALUE if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } // 下面就是扩容操作(2倍) else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) // threshold也变为二倍 newThr = oldThr << 1; } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // threshold为0,则使用默认值 newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { // 如果临界值还为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; }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; // 找Root for (TreeNode<K,V> p = root;;) { int dir, ph; K pk; if ((ph = p.hash) > h) // 红黑树中根据hash值、key值找结点 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)) 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; } } }treeifyBin()解析
// 链表转双向链表操作 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); if ((tab[index] = hd) != null) // 此处才是真正的转为红黑树 hd.treeify(tab); } }treeify()解析
//将链表中每个值进行红黑树插入操作 final void treeify(Node<K,V>[] tab) { TreeNode<K,V> root = null; // TreeNode<K,V> x = this 相当于初始化了一个结点 for (TreeNode<K,V> x = this, next; x != null; x = next) { next = (TreeNode<K,V>)x.next; // 初始化Root x.left = x.right = null; if (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;;) { int dir, ph; K pk = p.key; if ((ph = p.hash) > h) dir = -1; else if (ph < h) dir = 1; else if ((kc == null && // comparableClassFor(k) 返回 k 类型的比较器 (kc = comparableClassFor(k)) == null) || // compareComparables(kc, k, pk) 返回p,pk比较的结果 (dir = compareComparables(kc, k, pk)) == 0) // tieBreakOrder(k, pk) 比较两个hash码 dir = tieBreakOrder(k, pk); // 此处进行红黑树操作 TreeNode<K,V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { x.parent = xp; if (dir <= 0) xp.left = x; else xp.right = x; // 平衡调节 root = balanceInsertion(root, x); break; } } } } // 确保给定的根是根结点 moveRootToFront(tab, root); }balanceInsertion()解析
// 插入后的平衡操作 static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root, TreeNode<K,V> x) { x.red = true; for (TreeNode<K,V> xp, xpp, xppl, xppr;;) { // 没有结点时 if ((xp = x.parent) == null) { x.red = false; return x; } // 只有两层的树 else if (!xp.red || (xpp = xp.parent) == null) return root; // 左子树插入 if (xp == (xppl = xpp.left)) { if ((xppr = xpp.right) != null && xppr.red) { xppr.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.right) { root = rotateLeft(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateRight(root, xpp); } } } } // 右子树插入 else { // 祖父结点不为空,并且颜色为红色时 if (xppl != null && xppl.red) { xppl.red = false; xp.red = false; xpp.red = true; x = xpp; } else { // 左子树插入 if (x == xp.left) { root = rotateRight(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { // x 的父亲结点设置成黑色 xp.red = false; if (xpp != null) { // x的祖父结点设置成红色 xpp.red = true; // 左旋 root = rotateLeft(root, xpp); } } } } } }rotateLeft()解析 配图:
// 红黑树的左旋操作
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root, TreeNode<K,V> p) { // r(right) 指的是调整点的右子树根结点 // pp(parentparent) 是p的祖父结点 // rl(rigthleft) 是p的叔父结点 TreeNode<K,V> r, pp, rl; if (p != null && (r = p.right) != null) { if ((rl = p.right = r.left) != null) rl.parent = p; if ((pp = r.parent = p.parent) == null) (root = r).red = false; else if (pp.left == p) pp.left = r; else pp.right = r; r.left = p; p.parent = r; } return root; }