HashMap源码2
public class test { @SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] args) { HashMap1<Integer,String> hh = new HashMap1<Integer,String>(3); //链表添加 hh.put(0, "0"); hh.put(16, "16"); hh.put(16, "1616"); hh.put(32, "32"); hh.remove(16);//链表删除 hh.put(0, "00"); hh.put(48, "48"); hh.put(64, "64"); hh.put(80, "80"); hh.put(96, "96"); hh.put(112, "112"); hh.put(128, "128"); hh.put(144, "144");//0位置转成红黑树 hh.put(1, "1");//1位置链表添加 hh.put(16, "16");//0位置红黑树添加 hh.remove(96);//红黑树中间删除 hh.remove(64);//红黑树删除根节点 hh.remove(144);//红黑树删除叶子节点 hh.put(2, "2"); hh.put(3, "3"); hh.put(4, "4"); hh.put(5, "5"); hh.put(6, "6"); hh.put(7, "7"); Set s = hh.keySet();//[64, 0, 32, 96, 128, 1, 2, 3, 4, 5, 6, 7, 16, 48, 80, 112, 144] Iterator i = s.iterator(); if(i.hasNext()) System.out.println(i.next()); // i.remove(); if(i.hasNext()) System.out.println(i.next()); Spliterator v = s.spliterator(); // v.forEachRemaining(new Consumer() { // @Override // public void accept(Object t) { // System.out.println(t);//全部元素//[64, 0, 32, 96, 128, 1, 2, 3, 4, 5, 6, 7, 16, 48, 80, 112, 144] // } // }); Spliterator j = v.trySplit();//数组前面分割一般出去,后面留下 v.forEachRemaining(new Consumer() { @Override public void accept(Object t) { System.out.println(t);//16 48 80 112 144(有空元素) } }); j.forEachRemaining(new Consumer() { @Override public void accept(Object t) { System.out.println(t);//64, 0, 32, 96, 128, 1, 2, 3, 4, 5, 6, 7 } }); Spliterator j1 = j.trySplit(); j1.forEachRemaining(new Consumer() { @Override public void accept(Object t) { System.out.println(t); } }); j.forEachRemaining(new Consumer() { @Override public void accept(Object t) { System.out.println(t); } }); Spliterator kk = v.trySplit(); kk.forEachRemaining(new Consumer() { @Override public void accept(Object t) { System.out.println(t); } }); v.forEachRemaining(new Consumer() { @Override public void accept(Object t) { System.out.println(t); } }); HashMap1.tableSizeFor(128);//128:128,127:128,129:256,255:256,257:512 Set ss = hh.entrySet(); ss.forEach(new Consumer() { @Override public void accept(Object t) { System.out.println(t); } }); } }
package map; public class HashMap1<K,V> extends AbstractMap1<K,V> implements Map1<K,V>, Cloneable, Serializable { private static final long serialVersionUID = 362498820763181265L; static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//不直接写16,因为快,16也要转换为0 1, static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量,要是2的幂次方 //数组长度超过0.75就扩容。默认初始容量是16,加载因子是0.75。容量是哈希表中桶(Entry数组)的数量, //当哈希表中的条目数超出了加载因子与当前容量的乘积时,通过调用 rehash 方法将容量翻倍。 static final float DEFAULT_LOAD_FACTOR = 0.75f; //一个链表超过8个就变为红黑树 static final int TREEIFY_THRESHOLD = 8; //数组 public transient Node<K,V>[] table;//长度必须为2的幂 //大小,链表元素个数。 transient int size; transient int modCount;//用于快速失败。遍历时候不能修改。 int threshold;//capacity * load factor, 下次扩容的临界值,size>=threshold就会扩容 final float loadFactor;//负载因子可以改 static final int UNTREEIFY_THRESHOLD = 6; static final int MIN_TREEIFY_CAPACITY = 64;//数组长度小于64先扩容,先不转为红黑树, public static final int hash(Object key) { int h;//hashCode是native的,返回int。将hashCode的高16位参与运算 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//>>>左边补0 } //如果x实现了Comparable接口,则返回 x的Class。 public static Class<?> comparableClassFor(Object x) { if (x instanceof Comparable) {//实现了Comparable接口 Class<?> c; Type[] ts, as; Type t; ParameterizedType p; if ((c = x.getClass()) == String.class) //String就返回String return c; if ((ts = c.getGenericInterfaces()) != null) {//所有的接口,只要有一个接口是Comparable for (int i = 0; i < ts.length; ++i) { if (((t = ts[i]) instanceof ParameterizedType) && ((p = (ParameterizedType)t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && as[0] == c) // type arg is c return c; } } } return null; } //Returns k.compareTo(x) if x matches kc public static int compareComparables(Class<?> kc, Object k, Object x) { return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x)); } public static final int tableSizeFor(int cap) { //128:128,127:128,129:256,255:256,257:512。 //负数:32位,最高位是1,最后32位全是1,就返回-1。 //正数:最高位开始全是1:2^n - 1 + 1,就是最近大的2的幂次方 int n = cap- 1;//如果cap就是2的幂次方,就不要找最近的大了,就是自己。 System.out.println(Integer.toBinaryString(n)); n |= n >>> 1; System.out.println(Integer.toBinaryString(n)); n |= n >>> 2; System.out.println(Integer.toBinaryString(n)); n |= n >>> 4; System.out.println(Integer.toBinaryString(n)); n |= n >>> 8; System.out.println(Integer.toBinaryString(n)); n |= n >>> 16; System.out.println(Integer.toBinaryString(n));//32位全部变成1, System.out.println(n); return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; } transient Set<Map1.Entry<K,V>> entrySet; //负载因子小,数组就大,内存占用大,由于数组多那么就会导致链表短,数组查找O(1)链表短那么查找就快,负载因子小数组就小,链表就长,内存小,由于链表长了,查找时间慢。 //加载因子这里是可以大于1的。 public HashMap1(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);//临界值,最近大的2的幂次方。此时容量是0。 } public HashMap1(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap1() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } public HashMap1(Map1<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); } public final void putMapEntries(Map1<? extends K, ? extends V> m, boolean evict) {//通过entrySet来put int s = m.size(); if (s > 0) { if (table == null) { // pre-size 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) resize(); for (Map1.Entry<? extends K, ? extends V> e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); } } } public int size() { return size; } public boolean isEmpty() { return size == 0; } public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } public 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 && ((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; } public boolean containsKey(Object key) { return getNode(hash(key), key) != null; } public V put(K key, V value) {//已经存在就替换 return putVal(hash(key), key, value, false, true); } public final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {//onlyIfAbsent=true已经存在就不修改旧值。 Node<K,V>[] tab;//数组table Node<K,V> p/*tab[i]的元素*/; int n/*数组长度*/, i/*所在数组的索引*/; if ((tab = table) == null || (n = tab.length) == 0)//为空就去初始化。 n = (tab = resize()).length;//&运算比取模效率高很多, if ((p = tab[i = (n - 1) & hash]) == null)//(table.length - 1) & hash(key)是要放的位置,对table.length取余。数组长度要是2的幂次方。 tab[i] = newNode(hash, key, value, null);//为null直接放 else {//数组上也就是链表头有元素, Node<K,V> e/*找到的元素*/; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //就是链表的头结点替换 else if (p instanceof TreeNode)//红黑树节点是TreeNode,链表节点是Node e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else {//不是头结点,向下找, for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) {//链表末尾 //节点的hash就是key的hash。 p.next = newNode(hash, key, value, null);//放在链表末尾,链表添加节点。 if (binCount >= TREEIFY_THRESHOLD - 1) //7,== null:已经走到了末尾,就计算一直到末尾有多少个元素。已经有8个添加第9个元素时候treeifyBin() treeifyBin(tab, hash);//转成红黑树 break; } System.out.println(e.hash);//走到这里e!=null, if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))//e!=null,看是不是e,找到链表中这个节点e, break; p = e;//查找e下一个 } } if (e != null) { //e不等于null,找到的就是e,替换e。 V oldValue = e.value; if (!onlyIfAbsent || oldValue == null)//onlyIfAbsent=false就修改。 e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold)//链表节点总数大于阈值就扩容,不是数组非空个数大于阈值。 resize();//扩容 afterNodeInsertion(evict); return null; } public final Node<K,V>[] resize() {//初始化和扩容2倍,2个作用, Node<K,V>[] oldTab = table;//原来table作为旧的table, int oldCap = (oldTab == null) ? 0 : oldTab.length;//旧容量 int oldThr = threshold;//旧临界值 int newCap, newThr = 0;//新容量,新临界值 if (oldCap > 0) {//旧容量大于0 if (oldCap >= MAXIMUM_CAPACITY) {//旧容量大于1073741824 threshold = Integer.MAX_VALUE;//旧临界值=2147483647 return oldTab;//返回旧table } //旧容量乘以2小于最大值,就扩容2倍。临界值也变成2倍。 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; //临界值也变成2倍。 } else if (oldThr > 0) // 旧容量小于0,旧临界值大于0, newCap = oldThr;//新容量=旧临界值 else { // 旧容量小于0,旧临界值小于0, newCap = DEFAULT_INITIAL_CAPACITY;//新容量=16 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//12,size(链表个数)大于12就扩容,不是数组个数大于12. } if (newThr == 0) {//新临界值=0, float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; 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)//链表就一个元素,直接放,不就覆盖了?所有元素重新计算索引,不会覆盖。 //每列元素都是在自己位置或者加8(数组长度从16变成32)的位置,一个链表的元素不会抢占另一个链表元素的位置。 newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode)//红黑树 ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else {//链表,不是红黑树 //遍历一个链表时候,这个链表上的所有元素重新计算位置时候,要么在原来索引位置,要么在加8(数组长度从16变成32)的位置。 //所以就有2哥链表。 Node<K,V> loHead = null, loTail = null; //不动的元素,还在原来位置 Node<K,V> hiHead = null, hiTail = null; //加上8的位置的元素 Node<K,V> next; do {//遍历数组某一列的所有元素 next = e.next; if ((e.hash & oldCap) == 0) {//不动的元素,还在原来位置 //0,1,2,3,4,5,6,7,8*2,8*4,8*8,8*16.......的组合。原始容量是8扩容后是16。对8和16取余不变,所以索引位置不变。 if (loTail == null) loHead = e;//0=00,32=32,64=64,96=96,128=128,16扩容变成32后,32的倍数不变, else loTail.next = e; loTail = e; } else {//8 + 0,1,2,3,4,5,6,7,8*2,8*4,8*8,8*16.......的组合。取余加上8即可。 if (hiTail == null) hiHead = e;//48=48,80=80,112=112,144=144,16扩容变成32后,16奇数被的放到+16位置, 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; } public final void treeifyBin(Node<K,V>[] tab, int hash) {//hash位置的链表转为红黑树 int n = tab.length, index; Node<K,V> e; /*if (tab == null || n < MIN_TREEIFY_CAPACITY)//数组长度小于64先扩容,先不转为红黑树, resize();//注释掉,转为红黑树测试。 else*/ if ((e = tab[index = (n - 1) & hash]) != null) {//e有9个元素,e是第一个。 TreeNode<K,V> hd = null, tl = null; do { TreeNode<K,V> p = replacementTreeNode(e, null);//new TreeNode<>(p.hash, p.key, p.value, null); //TreeNode有parent,left,right,prev,before, after,hash,key,value,next; 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);//从头开始,把这个链表变成红黑树。hd可能不再是tab[index],因为红黑树顶点会变成一个新的,不一定是hd。 } } public void putAll(Map1<? extends K, ? extends V> m) { putMapEntries(m, true); } public V remove(Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; } public 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/*查找的索引*/; 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; 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)//头结点是红黑树 node = ((TreeNode<K,V>)p).getTreeNode(hash, key);//红黑树查找,从头结点开始查找, else {//头结点不是红黑树 do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } } if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) {//matchValue=false就根据key删除不根据value if (node instanceof TreeNode)//头结点是红黑树 ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);//红黑树删除 else if (node == p)//第一个元素直接替换 tab[index] = node.next; else p.next = node.next;//改变指针 ++modCount; --size; afterNodeRemoval(node); return node; } } return null; } public void clear() { Node<K,V>[] tab; modCount++; if ((tab = table) != null && size > 0) { size = 0; for (int i = 0; i < tab.length; ++i) tab[i] = null;//数组每个第一个元素置位null。 } } public boolean containsValue(Object value) { Node<K,V>[] tab; V v; if ((tab = table) != null && size > 0) { for (int i = 0; i < tab.length; ++i) {//先遍历数组 for (Node<K,V> e = tab[i]; e != null; e = e.next) {//再遍历链表 if ((v = e.value) == value || (value != null && value.equals(v))) return true; } } } return false; } @Override public V getOrDefault(Object key, V defaultValue) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? defaultValue : e.value; } @Override public V putIfAbsent(K key, V value) { return putVal(hash(key), key, value, true, true); } @Override public boolean remove(Object key, Object value) { return removeNode(hash(key), key, value, true, true) != null; } @Override public boolean replace(K key, V oldValue, V newValue) { Node<K,V> e; V v; if ((e = getNode(hash(key), key)) != null && ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) { e.value = newValue; afterNodeAccess(e); return true; } return false; } @Override public V replace(K key, V value) { Node<K,V> e; if ((e = getNode(hash(key), key)) != null) { V oldValue = e.value; e.value = value; afterNodeAccess(e); return oldValue; } return null; } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { if (mappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first/*第一个元素*/; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;//扩容或者初始化 if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; //找到的元素 K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e;//找到元素 break; } ++binCount; } while ((e = e.next) != null); } V oldValue; if (old != null && (oldValue = old.value) != null) { afterNodeAccess(old); return oldValue; } } V v = mappingFunction.apply(key); if (v == null) { return null; } else if (old != null) { old.value = v; afterNodeAccess(old); return v; } else if (t != null) t.putTreeVal(this, tab, hash, key, v); else { tab[i] = newNode(hash, key, v, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } ++modCount; ++size; afterNodeInsertion(true); return v; } public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { if (remappingFunction == null) throw new NullPointerException(); Node<K,V> e; V oldValue; int hash = hash(key); if ((e = getNode(hash, key)) != null && (oldValue = e.value) != null) { V v = remappingFunction.apply(key, oldValue); if (v != null) { e.value = v; afterNodeAccess(e); return v; } else removeNode(hash, key, null, false, true); } return null; } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { if (remappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;//扩容或者初始化 if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e; break; } ++binCount; } while ((e = e.next) != null); } } V oldValue = (old == null) ? null : old.value; V v = remappingFunction.apply(key, oldValue); if (old != null) { if (v != null) { old.value = v; afterNodeAccess(old); } else removeNode(hash, key, null, false, true); } else if (v != null) { if (t != null) t.putTreeVal(this, tab, hash, key, v); else { tab[i] = newNode(hash, key, v, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } ++modCount; ++size; afterNodeInsertion(true); } return v; } @Override public V merge(K key, V value,BiFunction<? super V, ? super V, ? extends V> remappingFunction) { if (value == null) throw new NullPointerException(); if (remappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e; break; } ++binCount; } while ((e = e.next) != null); } } if (old != null) { V v; if (old.value != null) v = remappingFunction.apply(old.value, value); else v = value; if (v != null) { old.value = v; afterNodeAccess(old); } else removeNode(hash, key, null, false, true); return v; } if (value != null) { if (t != null) t.putTreeVal(this, tab, hash, key, value); else { tab[i] = newNode(hash, key, value, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } ++modCount; ++size; afterNodeInsertion(true); } return value; } @Override public void forEach(BiConsumer<? super K, ? super V> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.key, e.value);//链表也遍历 } if (modCount != mc) throw new ConcurrentModificationException(); } } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Node<K,V>[] tab; if (function == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) { e.value = function.apply(e.key, e.value);//链表也遍历 } } if (modCount != mc) throw new ConcurrentModificationException(); } } @Override public Object clone() { HashMap1<K,V> result; try { result = (HashMap1<K,V>)super.clone(); } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } result.reinitialize(); result.putMapEntries(this, false); return result; } final float loadFactor() { return loadFactor; } final int capacity() { return (table != null) ? table.length : (threshold > 0) ? threshold : DEFAULT_INITIAL_CAPACITY; } private void writeObject(java.io.ObjectOutputStream s) throws IOException { int buckets = capacity(); // Write out the threshold, loadfactor, and any hidden stuff s.defaultWriteObject(); s.writeInt(buckets); s.writeInt(size); internalWriteEntries(s); } void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException { Node<K,V>[] tab; if (size > 0 && (tab = table) != null) { for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) { s.writeObject(e.key);//一个个的写出去 s.writeObject(e.value); } } } } private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the threshold (ignored), loadfactor, and any hidden stuff s.defaultReadObject(); reinitialize(); if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new InvalidObjectException("Illegal load factor: " + loadFactor); s.readInt(); // Read and ignore number of buckets int mappings = s.readInt(); // Read number of mappings (size) if (mappings < 0) throw new InvalidObjectException("Illegal mappings count: " + mappings); else if (mappings > 0) { // (if zero, use defaults) // Size the table using given load factor only if within // range of 0.25...4.0 float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f); float fc = (float)mappings / lf + 1.0f; int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ? DEFAULT_INITIAL_CAPACITY : (fc >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int)fc)); float ft = (float)cap * lf; threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ? (int)ft : Integer.MAX_VALUE); // Check Map.Entry[].class since it's the nearest public type to // what we're actually creating. SharedSecrets.getJavaOISAccess().checkArray(s, Map1.Entry[].class, cap); Node<K,V>[] tab = (Node<K,V>[])new Node[cap]; table = tab; // Read the keys and values, and put the mappings in the HashMap for (int i = 0; i < mappings; i++) { K key = (K) s.readObject(); V value = (V) s.readObject(); putVal(hash(key), key, value, false, false); } } } Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) { return new Node<>(hash, key, value, next); } Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) { return new Node<>(p.hash, p.key, p.value, next); } TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) { return new TreeNode<>(hash, key, value, next); } TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) { return new TreeNode<>(p.hash, p.key, p.value, next); } //重新初始化,Called by clone and readObject. void reinitialize() { table = null; entrySet = null; keySet = null; values = null; modCount = 0; threshold = 0; size = 0; } // LinkedHashMap使用:后置动作,LinkedHashMap extends HashMap void afterNodeAccess(Node<K,V> p) { } void afterNodeInsertion(boolean evict) { } void afterNodeRemoval(Node<K,V> p) { } /* ---------Map里面需要输出集合,并且遍历集合,还有分割。--------------------------------------------------- */ public Set<K> keySet() { Set<K> ks = keySet; if (ks == null) { ks = new KeySet(); keySet = ks; } return ks; } final class KeySet extends AbstractSet<K> { public final int size() { return size; } public final void clear() { HashMap1.this.clear(); } public final Iterator<K> iterator() { return new KeyIterator(); } public final boolean contains(Object o) { return containsKey(o); } public final boolean remove(Object key) { return removeNode(hash(key), key, null, false, true) != null; } public final Spliterator<K> spliterator() { return new KeySpliterator<>(HashMap1.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super K> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.key); } if (modCount != mc) throw new ConcurrentModificationException(); } } } public Collection<V> values() { Collection<V> vs = values; if (vs == null) { vs = new Values(); values = vs; } return vs; } final class Values extends AbstractCollection<V> { public final int size() { return size; } public final void clear() { HashMap1.this.clear(); } public final Iterator<V> iterator() { return new ValueIterator(); } public final boolean contains(Object o) { return containsValue(o); } public final Spliterator<V> spliterator() { return new ValueSpliterator<>(HashMap1.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super V> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) {//直接使用外部类的属性table int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.value); } if (modCount != mc) throw new ConcurrentModificationException(); } } } public Set<Map1.Entry<K,V>> entrySet() { Set<Map1.Entry<K,V>> es; es = entrySet == null ? (entrySet = new EntrySet()) : entrySet; System.out.println(es); return es; } final class EntrySet extends AbstractSet<Map1.Entry<K,V>> { public final int size() { return size; } public final void clear() { HashMap1.this.clear(); } public final Iterator<Map1.Entry<K,V>> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map1.Entry)) return false; Map1.Entry<?,?> e = (Map1.Entry<?,?>) o; Object key = e.getKey(); Node<K,V> candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map1.Entry) { Map1.Entry<?,?> e = (Map1.Entry<?,?>) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator<Map1.Entry<K,V>> spliterator() { return new EntrySpliterator<>(HashMap1.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super Map1.Entry<K,V>> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } } abstract class HashIterator { Node<K,V> next; // next entry to return Node<K,V> current; // current entry int expectedModCount; // for fast-fail int index; // current slot HashIterator() { expectedModCount = modCount; Node<K,V>[] t = table; current = next = null;//current是刚刚出去的节点,next是还没有出去的节点。 index = 0;//遍历时候,所在数组索引。 if (t != null && size > 0) { do {//初始化时候,next=数组中第一个不为null的元素,也是这个链表的头元素。 } while (index < t.length && (next = t[index++]) == null); } } public final boolean hasNext() { return next != null; } final Node<K,V> nextNode() { Node<K,V>[] t; Node<K,V> e = next; if (modCount != expectedModCount)//遍历时候不能修改 throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); if ((next = (current = e).next) == null && (t = table) != null) {//链表末尾了 do {} while (index < t.length && (next = t[index++]) == null);//找下一个数组元素,也就是新的链表头元素。 } return e; } public final void remove() {//移出去current Node<K,V> p = current; if (p == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); current = null; K key = p.key; removeNode(hash(key), key, null, false, false);//modCount++,就不能遍历了?下面修改expectedModCount为新的modCount。 expectedModCount = modCount; } } final class KeyIterator extends HashIterator implements Iterator<K> { public final K next() { return nextNode().key; } } final class ValueIterator extends HashIterator implements Iterator<V> { public final V next() { return nextNode().value; } } final class EntryIterator extends HashIterator implements Iterator<Map1.Entry<K,V>> { public final Map1.Entry<K,V> next() { return nextNode(); } } static class HashMapSpliterator<K,V> { final HashMap1<K,V> map; Node<K,V> current; int index; //开始位置 int fence; //结束位置 int est; //大小 int expectedModCount; HashMapSpliterator(HashMap1<K,V> m, int origin, int fence, int est, int expectedModCount) { this.map = m; this.index = origin;//开始位置 this.fence = fence;//结束位置 this.est = est;//大小 this.expectedModCount = expectedModCount; } final int getFence() { int hi; if ((hi = fence) < 0) { HashMap1<K,V> m = map; est = m.size; expectedModCount = m.modCount; Node<K,V>[] tab = m.table; hi = fence = (tab == null) ? 0 : tab.length; } return hi; } public final long estimateSize() { getFence(); // force init return (long) est; } } static final class KeySpliterator<K,V> extends HashMapSpliterator<K,V> implements Spliterator<K> { KeySpliterator(HashMap1<K,V> m, int origin, int fence, int est, int expectedModCount) { super(m, origin, fence, est, expectedModCount);//new KeySpliterator<>(HashMap1.this, 0, -1, 0, 0); } public KeySpliterator<K,V> trySplit() {//把数组切割分出去 int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid || current != null) ? null : new KeySpliterator<>(map, lo, index = mid, est >>>= 1, expectedModCount); } public void forEachRemaining(Consumer<? super K> action) { int i, hi, mc; if (action == null) throw new NullPointerException(); HashMap1<K,V> m = map; Node<K,V>[] tab = m.table; if ((hi = fence) < 0) { mc = expectedModCount = m.modCount; hi = fence = (tab == null) ? 0 : tab.length; } else mc = expectedModCount; if (tab != null && tab.length >= hi && (i = index) >= 0 && (i < (index = hi) || current != null)) { Node<K,V> p = current; current = null; do { if (p == null) p = tab[i++]; else { action.accept(p.key); p = p.next; } } while (p != null || i < hi);//数组链表都要遍历 if (m.modCount != mc) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super K> action) { int hi; if (action == null) throw new NullPointerException(); Node<K,V>[] tab = map.table; if (tab != null && tab.length >= (hi = getFence()) && index >= 0) { while (current != null || index < hi) {//数组链表都要遍历 if (current == null) current = tab[index++]; else { K k = current.key; current = current.next; action.accept(k); if (map.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } } } return false; } public int characteristics() { return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) | Spliterator.DISTINCT; } } static final class ValueSpliterator<K,V> extends HashMapSpliterator<K,V> implements Spliterator<V> { ValueSpliterator(HashMap1<K,V> m, int origin, int fence, int est, int expectedModCount) { super(m, origin, fence, est, expectedModCount);//new ValueSpliterator<>(HashMap1.this, 0, -1, 0, 0); } public ValueSpliterator<K,V> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid || current != null) ? null : new ValueSpliterator<>(map, lo, index = mid, est >>>= 1, expectedModCount); } public void forEachRemaining(Consumer<? super V> action) { int i, hi, mc; if (action == null) throw new NullPointerException(); HashMap1<K,V> m = map; Node<K,V>[] tab = m.table; if ((hi = fence) < 0) { mc = expectedModCount = m.modCount; hi = fence = (tab == null) ? 0 : tab.length; } else mc = expectedModCount; if (tab != null && tab.length >= hi && (i = index) >= 0 && (i < (index = hi) || current != null)) { Node<K,V> p = current; current = null; do { if (p == null) p = tab[i++]; else { action.accept(p.value); p = p.next; } } while (p != null || i < hi); if (m.modCount != mc) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super V> action) { int hi; if (action == null) throw new NullPointerException(); Node<K,V>[] tab = map.table; if (tab != null && tab.length >= (hi = getFence()) && index >= 0) { while (current != null || index < hi) { if (current == null) current = tab[index++]; else { V v = current.value; current = current.next; action.accept(v); if (map.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } } } return false; } public int characteristics() { return (fence < 0 || est == map.size ? Spliterator.SIZED : 0); } } static final class EntrySpliterator<K,V> extends HashMapSpliterator<K,V> implements Spliterator<Map1.Entry<K,V>> { EntrySpliterator(HashMap1<K,V> m, int origin, int fence, int est, int expectedModCount) { super(m, origin, fence, est, expectedModCount);//new EntrySpliterator<>(HashMap1.this, 0, -1, 0, 0); } public EntrySpliterator<K,V> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid || current != null) ? null : new EntrySpliterator<>(map, lo, index = mid, est >>>= 1, expectedModCount); } public void forEachRemaining(Consumer<? super Map1.Entry<K,V>> action) { int i, hi, mc; if (action == null) throw new NullPointerException(); HashMap1<K,V> m = map; Node<K,V>[] tab = m.table; if ((hi = fence) < 0) { mc = expectedModCount = m.modCount; hi = fence = (tab == null) ? 0 : tab.length; } else mc = expectedModCount; if (tab != null && tab.length >= hi && (i = index) >= 0 && (i < (index = hi) || current != null)) { Node<K,V> p = current; current = null; do { if (p == null) p = tab[i++]; else { action.accept(p); p = p.next; } } while (p != null || i < hi); if (m.modCount != mc) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super Map1.Entry<K,V>> action) { int hi; if (action == null) throw new NullPointerException(); Node<K,V>[] tab = map.table; if (tab != null && tab.length >= (hi = getFence()) && index >= 0) { while (current != null || index < hi) { if (current == null) current = tab[index++]; else { Node<K,V> e = current; current = current.next; action.accept(e); if (map.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } } } return false; } public int characteristics() { return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) | Spliterator.DISTINCT; } } /* ---------Map里面需要输出集合,并且遍历集合。--------------------------------------------------- */ // HashMap1.TreeNode extends LinkedHashMap1.Entry extends HashMap1.Node implements Map.Entry, static final class TreeNode<K,V> extends LinkedHashMap1.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); } // public final TreeNode<K,V> getParent() { return parent; } // public final TreeNode<K,V> getLeft() { return left; } // public final TreeNode<K,V> getRight() { return right; } // public final TreeNode<K,V> getPrev() { return prev; } public String toString() { return "key:"+key+",val:"+value+(red==true?",红":",黑"); // +(next!=null?",next:("+next.toString()+")":"") //不能造成递归toString() // +(prev!=null?",prev:"+prev.key:"") // +(parent!=null?",parent:"+parent.key:"") // +(left!=null?",left:("+left.toString()+")":"") // +(right!=null?",right:("+right.toString()+")":""); } //包含这个节点的树的根节点 final TreeNode<K,V> root() { for (TreeNode<K,V> r = this, p;;) { if ((p = r.parent) == null)//一直找父节点,就会找到根, return r; r = p; } } //红黑树根节点是数组的链表的第一个元素。红黑树和链表特性同时存在。 static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) { int n; if (root != null && tab != null && (n = tab.length) > 0) { int index = (n - 1) & root.hash;//root节点所在数组的索引 TreeNode<K,V> first = (TreeNode<K,V>)tab[index]; if (root != first) {//根节点变换了 Node<K,V> rn; tab[index] = root;//红黑树的根设置给数组元素 TreeNode<K,V> rp = root.prev; if ((rn = root.next) != null) ((TreeNode<K,V>)rn).prev = rp; if (rp != null) rp.next = rn;//把root从链表的prev和next中移除, if (first != null) first.prev = root; root.next = first; root.prev = null; } boolean b = checkInvariants(root); assert b; } } final TreeNode<K,V> find(int h, Object k, Class<?> kc) {//查找节点 TreeNode<K,V> p = this;// this为调用此方法的节点 do { int ph, dir; K pk; TreeNode<K,V> pl = p.left, pr = p.right, q; if ((ph = p.hash) > h) p = pl; else if (ph < h) p = pr; else if ((pk = p.key) == k || (k != null && k.equals(pk))) return p; else if (pl == null) p = pr; else if (pr == null) p = pl; else if ((kc != null || // comparableClassFor是如果key实现了Comparable就返回具体类型,否则返回null // compareComparables是比较传入的key和当前遍历元素的key // 只有当前hash值与传入的hash值一致才会走到这里 //如果传入的key(k)所属的类实现了Comparable接口,则将传入的key跟p节点的key比较 (kc = comparableClassFor(k)) != null) && // 此行不为空代表k实现了Comparable (dir = compareComparables(kc, k, pk)) != 0)//k<pk则dir<0, k>pk则dir>0 p = (dir < 0) ? pl : pr;// k < pk则向左遍历(p赋值为p的左节点), 否则向右遍历 //代码走到此处, 代表key所属类没有实现Comparable, 直接指定向p的右边遍历 else if ((q = pr.find(h, k, kc)) != null) return q; else// 代码走到此处代表上一个向右遍历(pr.find(h, k, kc))为空, 因此直接向左遍历 p = pl; } while (p != null); return null; } // 查找节点 final TreeNode<K,V> getTreeNode(int h, Object k) { return ((parent != null) ? root() : this).find(h, k, null); } // 用于不可比较或者hashCode相同时进行比较的方法 static int tieBreakOrder(Object a, Object b) { int d;//a b类的名字相等 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; } //返回根节点 final void treeify(Node<K,V>[] tab) { TreeNode<K,V> root = null; for (TreeNode<K,V> x = this, next; x != null; x = next) {//遍历放每一个节点 next = (TreeNode<K,V>)x.next; 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)//根节点 > x dir = -1;//左边 else if (ph < h)//根节点 < x dir = 1;//右边 //相等 else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) dir = tieBreakOrder(k, pk);//Hash(k) <= Hash(pk) ? -1 : 1,小于根节点在根的左边,大于根节点在根的右边。 TreeNode<K,V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) {//放到左边就看p.left,放到右边就看p.right。不为null就放,为null就继续指向左或者右节点。 x.parent = xp; if (dir <= 0) xp.left = x; else xp.right = x; root = balanceInsertion(root, x);//重新调整平衡树,返回新的root。 break;//跳出 } } } }//红黑树构造完在moveRootToFront()。红黑树根节点是数组的第一个元素 moveRootToFront(tab, root);//root节点可能不是原来第一个节点, } //红黑树太少了变成链表 final Node<K,V> untreeify(HashMap1<K,V> map) { Node<K,V> hd = null, tl = null;//头尾节点 for (Node<K,V> q = this; q != null; q = q.next) {//this是first节点。红黑树里面的next属性,就是为了以后少了的时候变成红黑树用的。 Node<K,V> p = map.replacementNode(q, null);//创建new Node()节点, if (tl == null) hd = p; else tl.next = p; tl = p; } return hd; } //红黑是添加节点,不是链表添加节点 final TreeNode<K,V> putTreeVal(HashMap1<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)//h在p左边 dir = -1; else if (ph < h)//h在p右边 dir = 1; else if ((pk = p.key) == k || (k != null && k.equals(pk)))//h=p return p; // comparableClassFor是如果key实现了Comparable就返回具体类型,否则返回null // compareComparables是比较传入的key和当前遍历元素的key // 只有当前hash值与传入的hash值一致才会走到这里 // 如果k所属的类没有实现Comparable接口 或者 k和p节点的key相等 else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) { if (!searched) {//第一次符合条件, 该方法只有第一次才执行 TreeNode<K,V> q, ch; searched = true; // 从p节点的左节点和右节点分别调用find方法进行查找, 如果查找到目标节点则返回 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; }// 否则使用定义的一套规则来比较k和p节点的key的大小, 用来决定向左还是向右查找 dir = tieBreakOrder(k, pk);// dir<0则代表k<pk,则向p左边查找;反之亦然 } TreeNode<K,V> xp = p;//要放的时候的根节点 if ((p = (dir <= 0) ? p.left : p.right) == null) {//等于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; } } } //节点自己调用,删除自己,传进来整个map,整个table。一个链表维护了链表的前驱后继关系(便于后面删除,变少了,再次转换为链表时用),也维护了红黑树的关系。 final void removeTreeNode(HashMap1<K,V> map, Node<K,V>[] tab, boolean movable) { int n; if (tab == null || (n = tab.length) == 0) return; int index = (n - 1) & hash;//hash是这个要删除节点的hash,96 TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;//first是数组中链表的第一个,root是红黑树的根, TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;//96节点自己的prev,next。 if (pred == null)//根节点在第一个,没有prev,删除的是根节点。考虑空,只有一个元素,2个元素,3个元素。 tab[index] = first = succ;//链表头指向next,成为链表的第一个, else pred.next = succ;//链表关系重建 if (succ != null)//最后一个节点 succ.prev = pred; if (first == null)// tab[index]=null或者就一个元素 return; if (root.parent != null) root = root.root();//找根节点 if (root == null || root.right == null || (rl = root.left) == null || rl.left == null) { tab[index] = first.untreeify(map); // 红黑树转成链表,第一个节点来调用。已经删除节点了。 return; } TreeNode<K,V> p = this, pl = left, pr = right, replacement;//this=p是要删除的节点,left,right是左右节点 if (pl != null && pr != null) {//有左右节点。交换p和后继元素。 TreeNode<K, V> s/* 后驱 */ = pr/* p的右节点 */, sl/* 查找后驱时候用 */; while ((sl = s.left) != null) // 找删除节点p的后驱s s = sl;//一个节点只有左或者右节点,删除之后不会影响平衡性,如果有左右节点删除后会影响平衡性,所以先用后驱替代,后驱只有一个子节点,删除后驱不会影响平衡性。 boolean c = s.red; s.red = p.red; p.red = c; // p和后驱s交换颜色。 //交换p和p的后驱。 TreeNode<K, V> sr = s.right;/* 后驱右节点 */ TreeNode<K, V> pp = p.parent;/* 删除节点父节点 */ if (s == pr) { // p的后驱s是p的右节点,p的右节点没有左节点 p.parent = s; s.right = p;//先改变p和s的关系 } else { TreeNode<K,V> sp = s.parent; if ((p.parent = sp) != null) { if (s == sp.left) sp.left = p; else sp.right = p; } if ((s.right = pr) != null) pr.parent = s; } p.left = null;//p的left没有节点 if ((p.right = sr) != null) sr.parent = p; if ((s.left = pl) != null) pl.parent = s; if ((s.parent = pp) == null) root = s; else if (p == pp.left) pp.left = s; else pp.right = s; //交换p和p的后驱s完毕,指正交换完毕, if (sr != null)//后驱只有右节点,没有左节点,所以用后驱的右节点替代后驱,就是删除后驱。 replacement = sr; else replacement = p;//此时p在p的后驱的位置 } else if (pl != null)//没有右节点,只有左节点 replacement = pl;//左节点放到删除位置 else if (pr != null)//只有右节点,没有左节点 replacement = pr;//右节点放到删除位置 else//左右节点都没有 replacement = p; if (replacement != p) {//代替节点!=p,删除p节点,replacement移到p的位置, TreeNode<K,V> pp = replacement.parent = p.parent; if (pp == null) root = replacement; else if (p == pp.left) pp.left = replacement; else pp.right = replacement; p.left = p.right = p.parent = null; } //删除是黑节点,黑高变了,从replacement调整红黑树。 TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement); if (replacement == p) { // 删除p TreeNode<K,V> pp = p.parent; p.parent = null; if (pp != null) { if (p == pp.left) pp.left = null; else if (p == pp.right) pp.right = null; } } if (movable) moveRootToFront(tab, r);//把根节点移到链表的开头 } //红黑树扩容时候调用((TreeNode<K,V>)e).split(this, newTab, j, oldCap); final void split(HashMap1<K,V> map, Node<K,V>[] tab, int index, int bit) { TreeNode<K,V> b = this; // 2个链表 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; if ((e.hash & bit) == 0) {//扩容之后还在原来位置的 if ((e.prev = loTail) == null) loHead = e; else loTail.next = e; loTail = e; ++lc; } else {//扩容之后在原来位置 + oldCap的 if ((e.prev = hiTail) == null) hiHead = e; else hiTail.next = e; hiTail = e; ++hc; } } if (loHead != null) { if (lc <= UNTREEIFY_THRESHOLD)//小于6转成链表 tab[index] = loHead.untreeify(map);//红黑树节点太少了变成链表 else {//大于6转成红黑树 tab[index] = loHead; if (hiHead != null) // hiHead==null,说明就一个链表,红黑树没有拆散,直接用这个红黑树就可以。 loHead.treeify(tab);//loHead链表转成红黑树 } } if (hiHead != null) { if (hc <= UNTREEIFY_THRESHOLD)//小于6转成链表 tab[index + bit] = hiHead.untreeify(map); else {//大于6转成红黑树 tab[index + bit] = hiHead; if (loHead != null)//loHead = null,说明就一个链表,红黑树没有拆散,直接用这个红黑树就可以。 hiHead.treeify(tab);//hiHead链表转成红黑树 } } } // 左旋转p static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root, TreeNode<K,V> 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;//新的顶点变成新的根节点才修改root为新的顶点p.right,否则root不变还是原来的根。 else if (pp.left == p) pp.left = r; else pp.right = r; r.left = p; p.parent = r; } return root; } // 右旋转p static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root, TreeNode<K,V> p) { TreeNode<K,V> l, pp, lr; if (p != null && (l = p.left) != null) { if ((lr = p.left = l.right) != null) lr.parent = p; if ((pp = l.parent = p.parent) == null) (root = l).red = false;//新的顶点变成新的根节点才修改root为新的顶点p.left,否则root不变还是原来的根。 else if (pp.right == p) pp.right = l; else pp.left = l; l.right = p; p.parent = l; } return root; } //返回新的root 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) {//没有父节点。 插入0 x.red = false;//变黑,返回 return x;//就是根节点 } else if (!xp.red || (xpp = xp.parent) == null)//父节点黑色,没有爷爷节点 return root;//返回新的顶点。 插入32 if (xp == (xppl = xpp.left)) {//爷爷左边 if ((xppr = xpp.right) != null && xppr.red) {//爷爷右节点红色 xppr.red = false; xp.red = false; xpp.red = true; x = xpp;//父亲变黑,爷爷右节点变黑,爷爷变红,x指向爷爷继续判断。修改X。root不变,继续判断x。 } else {//爷爷右节点黑色 if (x == xp.right) {//父亲右边 root = rotateLeft(root, x = xp);//左旋父亲 ,返回新的顶点,不是返回根节点。没有break。修改X,XP,XPP。 xpp = (xp = x.parent) == null ? null : xp.parent;//root可能变成新的顶点,继续判断父亲。 } if (xp != null) {//父亲左边 //父亲变黑,爷爷变红,右旋转爷爷 xp.red = false; if (xpp != null) { xpp.red = true; root = rotateRight(root, xpp);//返回根节点。root可能变成新的顶点,继续判断x。 } } } } else {//爷爷右边 if (xppl != null && xppl.red) {//爷爷左边红色 xppl.red = false; xp.red = false; xpp.red = true; x = xpp;//父亲变黑,爷爷左边变黑,爷爷变红,x指向爷爷继续判断。root不变,继续判断爷爷。 插入64 96 128 } else {//爷爷左边黑色 if (x == xp.left) {//父亲左边 root = rotateRight(root, x = xp);//右旋转父亲。修改X,XP,XPP。root可能变成新的顶点,继续判断父亲。 xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) {//父亲右边 xp.red = false; if (xpp != null) { xpp.red = true; root = rotateLeft(root, xpp);//父亲变黑,爷爷变红,左旋转爷爷。可能root变成新的顶点,继续判断x。插入48 80 112 } } } } } } static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root, TreeNode<K,V> x) { for (TreeNode<K,V> xp, xpl, xpr;;) { if (x == null || x == root) return root; else if ((xp = x.parent) == null) { x.red = false; return x; } else if (x.red) { x.red = false; return root; } else if ((xpl = xp.left) == x) { if ((xpr = xp.right) != null && xpr.red) { xpr.red = false; xp.red = true; root = rotateLeft(root, xp); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr == null) x = xp; else { TreeNode<K,V> sl = xpr.left, sr = xpr.right; if ((sr == null || !sr.red) && (sl == null || !sl.red)) { xpr.red = true; x = xp; } else { if (sr == null || !sr.red) { if (sl != null) sl.red = false; xpr.red = true; root = rotateRight(root, xpr); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr != null) { xpr.red = (xp == null) ? false : xp.red; if ((sr = xpr.right) != null) sr.red = false; } if (xp != null) { xp.red = false; root = rotateLeft(root, xp); } x = root; } } } else { // symmetric if (xpl != null && xpl.red) { xpl.red = false; xp.red = true; root = rotateRight(root, xp); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl == null) x = xp; else { TreeNode<K,V> sl = xpl.left, sr = xpl.right; if ((sl == null || !sl.red) && (sr == null || !sr.red)) { xpl.red = true; x = xp; } else { if (sl == null || !sl.red) { if (sr != null) sr.red = false; xpl.red = true; root = rotateLeft(root, xpl); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl != null) { xpl.red = (xp == null) ? false : xp.red; if ((sl = xpl.left) != null) sl.red = false; } if (xp != null) { xp.red = false; root = rotateRight(root, xp); } x = root; } } } } } //从根开始检查整个树红黑特性,以及prev和next特性。 static <K,V> boolean checkInvariants(TreeNode<K,V> t) { TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode<K,V>)t.next; if (tb != null && tb.next != t)//前面节点的下一个节点 不等于 这个节点 return false; if (tn != null && tn.prev != t)//后面节点的前一个节点不等于这个节点 return false; if (tp != null && t != tp.left && t != tp.right)//parent.left!=这个节点,并且parent.right!=这个节点 return false; if (tl != null && (tl.parent != t || tl.hash > t.hash)) return false; if (tr != null && (tr.parent != t || tr.hash < t.hash)) return false; if (t.red && tl != null && tl.red && tr != null && tr.red)//不能2层红 return false; if (tl != null && !checkInvariants(tl)) return false; if (tr != null && !checkInvariants(tr)) return false; return true; } } // HashMap1.TreeNode extends LinkedHashMap1.Entry extends HashMap1.Node implements Map.Entry, static class Node<K,V> implements Map1.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 Node<K,V> getNext() { return next; } public String toString() { return key + "=" + value +","+ ((next != null) ? next.toString() : ""); } public final int hashCode() {//native方法 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 Map1.Entry) { Map1.Entry<?,?> e = (Map1.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } } }