TreeMap源码分析2
package map; import org.junit.Test; import com.mysql.cj.api.x.Collection; import map.TreeMap1.AscendingSubMap.AscendingEntrySetView; import map.TreeMap1.NavigableSubMap.SubMapEntryIterator; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.Spliterator; import java.util.TreeMap; import java.util.function.Consumer; public class TestRBT { @SuppressWarnings({ "unchecked", "rawtypes", "unused" }) public static void testInsert() throws Exception { System.out.println("computeRedLevel:"+TreeMap1.computeRedLevel(12)); TreeMap1<Integer, Integer> mapr = new TreeMap1<Integer, Integer>(); mapr.put(10, 10); mapr.put(12, 12); TreeMap1<Integer, Integer> map = new TreeMap1<Integer, Integer>(); map.put(0, 0); Set<Map.Entry<Integer, Integer>> ss2 = map.entrySet(); map.put(1, 1);//Eclipse移到map上面去显示的是map的toString()方法或者父类的toString()方法。 Set<Map.Entry<Integer, Integer>> ss1 = map.entrySet(); System.out.println(map.toString());//toString是AbstractMap1的方法 map.put(2, 2); map.put(3, 3); map.put(4, 4); map.put(5, 5); map.put(6, 6); map.put(7, 7); map.put(8, 8); map.put(9, 9); map.put(10, 10); Set<Map.Entry<Integer, Integer>> ss = map.entrySet(); // Collection c = (Collection) map.values(); TreeMap1<Integer, Integer> map1 = new TreeMap1<Integer, Integer>(map); map1.putAll(map); System.out.println(map1.toString());//5-BLACK-5 2-BLACK-2 8-BLACK-8 0-BLACK-0 3-BLACK-3 6-BLACK-6 9-BLACK-9 1-RED-1 4-RED-4 7-RED-7 10-RED-10 Spliterator s2 = map1.keySet().spliterator();//前面分割出去,留下来后面的。 Spliterator s21 = s2.trySplit();//分割出去的21:开始0结束root,side=-1,est=5。留下来的s2:开始root结束null,side=1,est=5 Spliterator s22 = s21.trySplit();//出去的再分割,出去前面的(0---root.left),留下来的(root.left----root) Spliterator s23 = s2.trySplit();//留下来的再分割, Spliterator s1 = map1.entrySet().spliterator(); Spliterator s11 = s1.trySplit(); Spliterator s3 = map1.values().spliterator(); AscendingEntrySetView sm = (AscendingEntrySetView) map1.subMap(3, 6).entrySet();//[[键=3,值=3,色=黑], [键=4,值=4,色=红], [键=5,值=5,色=黑]] int i = sm.size(); SubMapEntryIterator sit = (SubMapEntryIterator) sm.iterator(); while(sit.hasNext()) { System.out.println(sit.next()); } } public static void main(String[] args) throws Exception { testInsert(); } }
package map;//不是线程安全的,要想线程安全就要:SortedMap m = Collections.synchronizedSortedMap(new TreeMap1()); public class TreeMap1<K, V> extends AbstractMap1<K, V> implements NavigableMap<K, V>, Cloneable, Serializable { private final Comparator<? super K> comparator; private transient Entry<K, V> root;// 根节点 private transient int size = 0;// 节点个数 private transient int modCount = 0;// 修改次数 public Entry<K, V> Root(){ return root; } public TreeMap1() { //该类型的compareTo方法来比较大小。String类的compareTo方法比对大小,Integer的compareTo方法比对。 comparator = null; } public String toString() {//层序输出红黑树 TreeMap1.Entry root= this.root; if(root==null){ return ""; } StringBuffer sb = new StringBuffer(); Queue<Entry<K, V>> queue=new LinkedList<Entry<K, V>>(); queue.offer(root); int preCount=1; int pCount=0; while(!queue.isEmpty()){ Entry<K, V> p=queue.poll(); preCount--; printTreeNode(p,sb); if(p.getLeft()!=null){ queue.offer((Entry<K, V>)p.left); pCount++; } if((Entry<K, V>)p.right!=null){ queue.offer((Entry<K, V>)p.right); pCount++; } if(preCount==0){ preCount=pCount; pCount=0; } } return sb.toString(); } private static <K,V> void printTreeNode(Entry p,StringBuffer sb) { boolean color=p.color; String colorStr=""; if(color){ colorStr="BLACK"; }else{ colorStr="RED"; } sb.append(p.getKey()+"-"+colorStr+"-"+p.getValue()+" "); } public TreeMap1(Comparator<? super K> comparator) { this.comparator = comparator; } public TreeMap1(Map<? extends K, ? extends V> m) {//map不是有序的, comparator = null; putAll(m); } public TreeMap1(SortedMap<K, ? extends V> m) {//map有序,通过iterator遍历添加。TreeMap是有序的。 comparator = m.comparator(); try { buildFromSorted(m.size(), m.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } public int size() { return size; } public boolean containsKey(Object key) { return getEntry(key) != null; } public boolean containsValue(Object value) { for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e))// getFirstEntry() 是返回红黑树的第一个节点,successor(e) // 是获取节点e的后继节点。从第一个节点依次找后继。 if (valEquals(value, e.value)) return true; return false; } public V get(Object key) { Entry<K, V> p = getEntry(key); return (p == null ? null : p.value); } public Comparator<? super K> comparator() { return comparator; } public K firstKey() {// 获取第一个节点对应的key return key(getFirstEntry()); } public K lastKey() {// 获取最后一个节点对应的key return key(getLastEntry()); } // 已经有的key会替换 public void putAll(Map<? extends K, ? extends V> map) { int mapSize = map.size();// map是已排序的“key-value对” if (size == 0 && mapSize != 0 && map instanceof SortedMap) {// 没有元素就调用buildFromSorted方法 Comparator<?> c = ((SortedMap<?, ?>) map).comparator(); if (c == comparator || (c != null && c.equals(comparator))) { ++modCount; try { Set es = map.entrySet(); Iterator it = es.iterator();// map的iterator对象 buildFromSorted(mapSize, map.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return; } } super.putAll(map);// 有元素调用正常的put方法,调用AbstractMap中的putAll(),又会调用到TreeMap的put()。map不是排序的,也调用这里。 } public final Entry<K, V> getEntry(Object key) { if (comparator != null)// 若“比较器”为null,则通过getEntryUsingComparator()获取“键”为key的节点 return getEntryUsingComparator(key); if (key == null) throw new NullPointerException(); Comparable<? super K> k = (Comparable<? super K>) key; Entry<K, V> p = root; while (p != null) {// 依次找左右节点 int cmp = k.compareTo(p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } return null; } public final Entry<K, V> getEntryUsingComparator(Object key) {// 从根依次找左右节点, K k = (K) key; Comparator<? super K> cpr = comparator; if (cpr != null) { Entry<K, V> p = root; while (p != null) { int cmp = cpr.compare(k, p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } } return null; } public final Entry<K, V> getCeilingEntry(K key) {// key最近的大,可以相等 Entry<K, V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp < 0) {// 小就左找 if (p.left != null) p = p.left; else// 为null就是p return p; // p!=null因为在while循环里面,不可能这里返回null } else if (cmp > 0) {// 大就右找 if (p.right != null) { p = p.right; } else {// 为null就找p的后继 Entry<K, V> ch = p; Entry<K, V> parent = p.parent; while (parent != null && ch == parent.right) {// 左节点退出 ch = parent; parent = parent.parent; } return parent;// parent有可能这里返回null,就是都比key小,没有比key大的。 } } else// 相等就是这个 return p; } return null;// root=null, } public final Entry<K, V> getFloorEntry(K key) {// 最近的小,可以相等 Entry<K, V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp > 0) { if (p.right != null) p = p.right; else return p; } else if (cmp < 0) { if (p.left != null) { p = p.left; } else { Entry<K, V> parent = p.parent; Entry<K, V> ch = p; while (parent != null && ch == parent.left) {// 右节点退出 ch = parent; parent = parent.parent; } return parent; } } else return p; } return null; } public final Entry<K, V> getHigherEntry(K key) {// key最近的大,相等就往上再找最近的大。 Entry<K, V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp < 0) { if (p.left != null) p = p.left; else return p; } else {//相等找右边的,继续找大的。再次while肯定小于0。 if (p.right != null) { p = p.right; } else { Entry<K, V> parent = p.parent; Entry<K, V> ch = p; while (parent != null && ch == parent.right) {// 左节点退出 ch = parent; parent = parent.parent; } return parent; } } } return null; } public final Entry<K, V> getLowerEntry(K key) {// 最近的小,相等继续找小的。 Entry<K, V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp > 0) { if (p.right != null) p = p.right; else return p; } else {//相等找左边的,继续找小的。 if (p.left != null) { p = p.left; } else { Entry<K, V> parent = p.parent; Entry<K, V> ch = p; while (parent != null && ch == parent.left) { ch = parent; parent = parent.parent; } return parent; } } } return null; } public V put(K key, V value) { Entry<K, V> t = root; if (t == null) { compare(key, key); // 类型检查,有可能是null。 root = new Entry<>(key, value, null); size = 1; modCount++; return null; } int cmp; Entry<K, V> parent;// 2个指针,一个父节点一个子节点,指向查找过程中的parent,t。parent也是新加入节点的父节点,t是新加入节点的位置。 Comparator<? super K> cpr = comparator; if (cpr != null) { do { parent = t;// 修改parent为t,下面重新设置t, cmp = cpr.compare(key, t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null);// 一直t=null退出, } else { if (key == null) throw new NullPointerException(); Comparable<? super K> k = (Comparable<? super K>) key; do { parent = t;// 向下修改parent,下面重新设置t, cmp = k.compareTo(t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null);// t=null退出, } Entry<K, V> e = new Entry<>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e;// 插入元素完毕 fixAfterInsertion(e);// 从新插入的元素开始调整,依次向上移动,直到根节点退出。 size++;// 节点个数 modCount++; return null; } public V remove(Object key) { Entry<K, V> p = getEntry(key); if (p == null) return null; V oldValue = p.value; deleteEntry(p); return oldValue; } public void clear() { modCount++; size = 0; root = null; } public Object clone() {// 浅拷贝。 TreeMap1<?, ?> clone; try { clone = (TreeMap1<?, ?>) super.clone();// 类的成员变量如果是对象,地址也是一样的。 } catch (CloneNotSupportedException e) { throw new InternalError(e); } // 除了比较器,都设置为初始状态,重新设置成员变量的地址。 clone.root = null; clone.size = 0; clone.modCount = 0; clone.entrySet = null; clone.navigableKeySet = null; clone.descendingMap = null; try { clone.buildFromSorted(size, entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return clone; } public Map.Entry<K, V> firstEntry() { return exportEntry(getFirstEntry());//SimpleImmutableEntry封装0 } public Map.Entry<K, V> lastEntry() { return exportEntry(getLastEntry());//SimpleImmutableEntry封装 } public Map.Entry<K, V> pollFirstEntry() {// 获取第一个节点,并将改节点从TreeMap中删除。 Entry<K, V> p = getFirstEntry(); Map.Entry<K, V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } public Map.Entry<K, V> pollLastEntry() {// 获取最后一个节点,并将改节点从TreeMap中删除。 Entry<K, V> p = getLastEntry(); Map.Entry<K, V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } public Map.Entry<K, V> lowerEntry(K key) {// 返回小于key的最大的键值对, return exportEntry(getLowerEntry(key)); } public K lowerKey(K key) {// 返回小于key的最大的键值对所对应的KEY return keyOrNull(getLowerEntry(key)); } public Map.Entry<K, V> floorEntry(K key) {// 返回不大于key的最大的键值对 return exportEntry(getFloorEntry(key)); } public K floorKey(K key) {// 返回不大于key的最大的键值对所对应的KEY, return keyOrNull(getFloorEntry(key)); } public Map.Entry<K, V> ceilingEntry(K key) {// 返回不小于key的最小的键值对 return exportEntry(getCeilingEntry(key)); } public K ceilingKey(K key) {// 返回不小于key的最小的键值对所对应的KEY return keyOrNull(getCeilingEntry(key)); } public Map.Entry<K, V> higherEntry(K key) {// 返回大于key的最小的键值对 return exportEntry(getHigherEntry(key)); } public K higherKey(K key) {// 返回大于key的最小的键值对所对应的KEY, return keyOrNull(getHigherEntry(key)); } public transient EntrySet entrySet;// TreeMap的红黑树节点对应的集合 public transient KeySet<K> navigableKeySet;// TreeMap的红黑树节点对应的Key集合 public transient NavigableMap<K, V> descendingMap; final int compare(Object k1, Object k2) { return comparator == null ? ((Comparable<? super K>) k1).compareTo((K) k2) : comparator.compare((K) k1, (K) k2); } static final boolean valEquals(Object o1, Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } static <K, V> Map.Entry<K, V> exportEntry(Entry<K, V> e) { return (e == null) ? null : new SimpleImmutableEntry<>(e); } static <K, V> K keyOrNull(Entry<K, V> e) { return (e == null) ? null : e.key; } static <K> K key(Entry<K, ?> e) { if (e == null) throw new NoSuchElementException(); return e.key; } private static final boolean RED = false; private static final boolean BLACK = true; static final class Entry<K, V> implements Map.Entry<K, V> { public K key; public V value; public Entry<K, V> left; public Entry<K, V> right; public Entry<K, V> parent; boolean color = BLACK;// 默认黑色 Entry(K key, V value, Entry<K, V> parent) {// 默认是黑色 this.key = key; this.value = value; this.parent = parent; } public K getKey() { return key; } public V getValue() { return value; } public Entry<K, V> getLeft() { return left; } public Entry<K, V> setLeft(Entry<K, V> left) { this.left = left; return left; } public Entry<K, V> getRight() { return right; } public Entry<K, V> setRight(Entry<K, V> right) { this.right = right; return right; } public Entry<K, V> getParent() { return parent; } public Entry<K, V> setParent(Entry<K, V> parent) { this.parent = parent; return parent; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?, ?> e = (Map.Entry<?, ?>) o; return valEquals(key, e.getKey()) && valEquals(value, e.getValue()); } public int hashCode() { int keyHash = (key == null ? 0 : key.hashCode()); int valueHash = (value == null ? 0 : value.hashCode()); return keyHash ^ valueHash; } public String toString() { return "[键=" + key + ",值=" + value + ",色=" + (color == true ? "黑" : "红") + "]"; } } final Entry<K, V> getFirstEntry() {// 第一个元素,最左边的元素,最小的元素。 Entry<K, V> p = root; if (p != null) while (p.left != null) p = p.left; return p; } final Entry<K, V> getLastEntry() {// 最右边的元素 Entry<K, V> p = root; if (p != null) while (p.right != null) p = p.right; return p; } // t.right和t.right.left不为null,后继是叶子节点。 static <K, V> Entry<K, V> successor(Entry<K, V> t) {// 寻找t的后继结点 if (t == null) return null; else if (t.right != null) {// 有右子树,右子树的最左边, Entry<K, V> p = t.right; while (p.left != null) p = p.left; return p; } else {// 没有右子树 Entry<K, V> ch = t; Entry<K, V> p = t.parent; // 找到一个根节点,他在根节点左边 while (p != null && ch == p.right) { ch = p; p = p.parent; } return p; } } // t.left和t.left.right不为null,前驱是叶子节点。 static <K, V> Entry<K, V> predecessor(Entry<K, V> t) { if (t == null) return null; else if (t.left != null) {// 左子树的最右边 Entry<K, V> p = t.left; while (p.right != null) p = p.right; return p; } else {// 没有左子树 Entry<K, V> p = t.parent; Entry<K, V> ch = t; while (p != null && ch == p.left) {// 找到一个根节点,他在根节点右边 ch = p; p = p.parent; } return p; } } private static <K, V> boolean colorOf(Entry<K, V> p) { return (p == null ? BLACK : p.color);// null是黑节点 } private static <K, V> Entry<K, V> parentOf(Entry<K, V> p) { return (p == null ? null : p.parent); } private static <K, V> void setColor(Entry<K, V> p, boolean c) { if (p != null) p.color = c; } private static <K, V> Entry<K, V> leftOf(Entry<K, V> p) { return (p == null) ? null : p.left; } private static <K, V> Entry<K, V> rightOf(Entry<K, V> p) { return (p == null) ? null : p.right; } /* 旋转没有改变指针指向,但是改变了父子关系 */ private void rotateLeft(Entry<K, V> p) { if (p != null) { Entry<K, V> r = p.right;// ① p.right = r.left;// ② if (r.left != null) r.left.parent = p;// ③ r.parent = p.parent;// ④ if (p.parent == null) root = r; else if (p.parent.left == p) p.parent.left = r;// ⑤ else p.parent.right = r;// ⑤ r.left = p;// ⑥ p.parent = r;// ⑦ } } /* 旋转没有改变指针指向,但是改变了父子关系 */ private void rotateRight(Entry<K, V> p) { if (p != null) { Entry<K, V> l = p.left; p.left = l.right; if (l.right != null) l.right.parent = p; l.parent = p.parent; if (p.parent == null) root = l; else if (p.parent.right == p) p.parent.right = l; else p.parent.left = l; l.right = p; p.parent = l; } } /* 插入之后调整 */ private void fixAfterInsertion(Entry<K, V> x) { x.color = RED;// 新插入节点变成红色 // 向上到根退出,父节点是黑色退出,所以父节点一定是红色。 while (x != null && x != root && x.parent.color == RED) { if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {// x是爷爷的左边 Entry<K, V> y = rightOf(parentOf(parentOf(x)));// 爷爷的右节点 if (colorOf(y) == RED) {// 爷爷的右节点是红的,null是黑色。情况② setColor(parentOf(x), BLACK);// 设置父节点为黑色 setColor(y, BLACK);// 自己爷爷右子树为黑色 setColor(parentOf(parentOf(x)), RED);// 设置爷爷为红色 x = parentOf(parentOf(x));// x指向爷爷继续判断 } else {// 爷爷的右节点是黑的 if (x == rightOf(parentOf(x))) {// x在父节点右边。情况① x = parentOf(x);// x指向父亲 rotateLeft(x);// x又旋转下来,又指向儿子。 } setColor(parentOf(x), BLACK);// 父亲为黑。情况③ setColor(parentOf(parentOf(x)), RED);// 爷爷为红 rotateRight(parentOf(parentOf(x)));// 右旋转爷爷 } } else {// x是爷爷的右边 Entry<K, V> y = leftOf(parentOf(parentOf(x))); if (colorOf(y) == RED) {// 爷爷的左节点是红色。情况④ setColor(parentOf(x), BLACK);// 父亲为黑色 setColor(y, BLACK);// 爷爷左节点为黑色 setColor(parentOf(parentOf(x)), RED);// 爷爷为红色 x = parentOf(parentOf(x));// x指向爷爷,继续while循环 } else {// 爷爷的左节点是黑色1. if (x == leftOf(parentOf(x))) {// x在父亲左边。情况⑤ x = parentOf(x); rotateRight(x); } setColor(parentOf(x), BLACK);// 父亲黑色。情况⑥ setColor(parentOf(parentOf(x)), RED);// 爷爷红色 rotateLeft(parentOf(parentOf(x))); } } } root.color = BLACK; } private void deleteEntry(Entry<K, V> p) {// 12 modCount++; size--; // p有左右子节点,就把p替换成后驱的key和value,转而删除后驱。 if (p.left != null && p.right != null) { Entry<K, V> s = successor(p);// p.right和p.right.left不为null,后继是叶子节点。 p.key = s.key; p.value = s.value;// 修改key和value就可以了,left,right,parent不用改变。 p = s;// 转而去删除S } // 直接删除p,不用替换成后驱,不用转而删除后驱。 replacement替代p,replacement是p的左节点或者右节点。 Entry<K, V> replacement = (p.left != null ? p.left : p.right);// 10 if (replacement != null) { // 修改replacement的parent,以及p.parent的左或者右指针。 replacement.parent = p.parent;// 8 if (p.parent == null)// p是根节点 root = replacement; else if (p == p.parent.left) p.parent.left = replacement; else p.parent.right = replacement; p.left = p.right = p.parent = null;// GC if (p.color == BLACK)// 删除的p是黑色就调整,黑高变了。 fixAfterDeletion(replacement); } else if (p.parent == null) { // replacement=null,p的左右节点为null, p是孤立的点,就是根节点,现在移除根节点。 root = null; } else { // replacement=null,p的左右节点为null,p.parent != null,p是叶子节点,直接删除。 if (p.color == BLACK)// 删除的p是黑色就调整, fixAfterDeletion(p); if (p.parent != null) { if (p == p.parent.left) p.parent.left = null; else if (p == p.parent.right) p.parent.right = null; p.parent = null; } } } /** From CLR */ private void fixAfterDeletion(Entry<K, V> x) {// replacement是黑色 while (x != root && colorOf(x) == BLACK) { if (x == leftOf(parentOf(x))) {// 父节点左边 Entry<K, V> sib = rightOf(parentOf(x)); if (colorOf(sib) == RED) {// 父节点右边是红色 setColor(sib, BLACK); setColor(parentOf(x), RED); rotateLeft(parentOf(x));// x旋转到上面去了, sib = rightOf(parentOf(x));// sib指向爷爷节点 } // 爷爷左右是黑色 if (colorOf(leftOf(sib)) == BLACK && colorOf(rightOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x);// x指向爷爷 } else { if (colorOf(rightOf(sib)) == BLACK) { setColor(leftOf(sib), BLACK); setColor(sib, RED); rotateRight(sib); sib = rightOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(rightOf(sib), BLACK); rotateLeft(parentOf(x)); x = root; } } else { // 父节点右边 Entry<K, V> sib = leftOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateRight(parentOf(x)); sib = leftOf(parentOf(x)); } if (colorOf(rightOf(sib)) == BLACK && colorOf(leftOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(leftOf(sib)) == BLACK) { setColor(rightOf(sib), BLACK); setColor(sib, RED); rotateLeft(sib); sib = leftOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(leftOf(sib), BLACK); rotateRight(parentOf(x)); x = root; } } } setColor(x, BLACK); } /** Intended to be called only from TreeSet.readObject */ void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal) throws java.io.IOException, ClassNotFoundException { buildFromSorted(size, null, s, defaultVal); } /** Intended to be called only from TreeSet.addAll */ void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) { try { buildFromSorted(set.size(), set.iterator(), null, defaultVal); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } // 假设在调用此方法之前已经设置了树映射1的比较器。 private void buildFromSorted(int size, Iterator<?> it, java.io.ObjectInputStream str, V defaultVal) throws java.io.IOException, ClassNotFoundException { this.size = size; root = buildFromSorted(0, 0, size - 1, computeRedLevel(size), it, str, defaultVal); } //从排序的Map里面取出部分元素,构造新的TreeMap public final Entry<K, V> buildFromSorted(int level, int lo, int hi, int redLevel, Iterator<?> it, java.io.ObjectInputStream str, V defaultVal) throws java.io.IOException, ClassNotFoundException { if (hi < lo)//原Map的开始和截止位置 return null; int mid = (lo + hi) >>> 1; Entry<K, V> left = null; if (lo < mid) //左节点 left = buildFromSorted(level + 1, lo, mid - 1, redLevel, it, str, defaultVal); // extract key and/or value from iterator or stream K key; V value; if (it != null) { if (defaultVal == null) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) it.next();//遍历器从最左边开始,依次后继, key = (K) entry.getKey(); value = (V) entry.getValue(); } else { key = (K) it.next(); value = defaultVal; } } else { // use stream key = (K) str.readObject(); value = (defaultVal != null ? defaultVal : (V) str.readObject()); } Entry<K, V> middle = new Entry<>(key, value, null);//默认黑色 // 只将红黑树最底端的阶段着色为红色,其余都是黑色。 if (level == redLevel) middle.color = RED; if (left != null) {//连接左节点 middle.left = left; left.parent = middle; } if (mid < hi) {//连接右节点 Entry<K, V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal); middle.right = right; right.parent = middle; } return middle;//返回中间节点 } public static int computeRedLevel(int sz) {//1:1,2:1,3:2,4:2,5:2,6:2,7:3,8:3,9:3,10:3,11:3,12:3 int level = 0; for (int m = sz - 1; m >= 0; m = m / 2 - 1) level++; return level; } private static final long serialVersionUID = 919286545866124006L; @Override public boolean replace(K key, V oldValue, V newValue) { Entry<K, V> p = getEntry(key); if (p != null && Objects.equals(oldValue, p.value)) { p.value = newValue; return true; } return false; } @Override public V replace(K key, V value) { Entry<K, V> p = getEntry(key); if (p != null) { V oldValue = p.value; p.value = value; return oldValue; } return null; } @Override public void forEach(BiConsumer<? super K, ? super V> action) {//从第一个一直后驱 Objects.requireNonNull(action); int expectedModCount = modCount; for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) { action.accept(e.key, e.value); if (expectedModCount != modCount) { throw new ConcurrentModificationException(); } } } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {//从第一个一直寻找后驱 Objects.requireNonNull(function); int expectedModCount = modCount; for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) { e.value = function.apply(e.key, e.value); if (expectedModCount != modCount) { throw new ConcurrentModificationException(); } } } //-----------------------------------基本方法--------------------------------------- //---------------------------------Set-----------------Iterator---------------------------- //---Map有keySet()输出集合就有Set,Set有遍历和分割操作,所以有Iterator和Spliterator ---------子Map也有keySet和EntrySet-------- public Set<K> keySet() {// 修改map会影响keySet,修改keySet会影响map。 return navigableKeySet(); } public NavigableSet<K> navigableKeySet() {//KeySet KeySet<K> nks = navigableKeySet; return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));//this是TreeMap1 } public Collection<V> values() {// 修改map会影响values,修改values会影响map。 Collection<V> vs = values; if (vs == null) { vs = new Values();//是根据iterator()来确定值的,一定要有iterator()。是根据返回的ValueIterator的hasNext()和next()方法确定的。 values = vs; } return vs; } public Set<Map.Entry<K, V>> entrySet() {// 修改map会影响entrySet,修改entrySet会影响map。 EntrySet es = entrySet;// 没有值 boolean b = es != null; return (es != null) ? es : (entrySet = new EntrySet());// 有值 } class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return new ValueIterator(getFirstEntry()); // ArrayList<String> aList=new ArrayList<String>(); // aList.add("a"); // aList.add("b"); // return (Iterator<V>) aList.iterator(); } public int size() { return TreeMap1.this.size(); } public boolean contains(Object o) { return TreeMap1.this.containsValue(o); } public boolean remove(Object o) { for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) { if (valEquals(e.getValue(), o)) { deleteEntry(e); return true; } } return false; } public void clear() { TreeMap1.this.clear(); } public Spliterator<V> spliterator() { return new ValueSpliterator<K, V>(TreeMap1.this, null, null, 0, -1, 0); } // public String toString() {//Eclipse上vs = new Values()鼠标移到vs上显示的内容 // return "sss"; // } } class EntrySet extends AbstractSet<Map.Entry<K, V>> { public Iterator<Map.Entry<K, V>> iterator() { return new EntryIterator(getFirstEntry());// renturn null就没有值了。Set里面的遍历使用的是Iterator。从前往后遍历Entry。 } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; Object value = entry.getValue(); Entry<K, V> p = getEntry(entry.getKey());// 内部类可以直接访问外部类的方法 return p != null && valEquals(p.getValue(), value); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; Object value = entry.getValue(); Entry<K, V> p = getEntry(entry.getKey()); if (p != null && valEquals(p.getValue(), value)) { deleteEntry(p); return true; } return false; } public int size() { return TreeMap1.this.size(); } public void clear() { TreeMap1.this.clear(); } public String toString() {//鼠标移上去显示的内容 Iterator<Map.Entry<K, V>> i = iterator(); if (! i.hasNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append("{¥"); for (;;) { Map.Entry<K,V> e = i.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (!i.hasNext()) return sb.append('}').toString(); sb.append(',').append(' '); } } public Spliterator<Map.Entry<K, V>> spliterator() {//Entry分割器 return new EntrySpliterator<K, V>(TreeMap1.this, null, null, 0, -1, 0); } } //KeySet里面有NavigableMap,KeySet比Values和EntrySet要复杂。KeySet里面有m,Values和EntrySet里面没有m。m可以是TreeMap1也可以是TreeMap1的子Map。 //Values和EntrySet就要调用TreeMap1.this对象和外部类TreeMap1的方法。KeySet直接调用m的方法。 static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {// KeySet是静态的 private final NavigableMap<E, ?> m;// NavigableMap是接口,对TreeMap的封装。 KeySet(NavigableMap<E, ?> map) { m = map; } public Iterator<E> iterator() {//使用KeyIterator。Set里面的遍历使用的是Iterator。从前往后遍历Key。 if (m instanceof TreeMap1) return ((TreeMap1<E, ?>) m).keyIterator(); else return ((NavigableSubMap<E, ?>) m).keyIterator(); } public Iterator<E> descendingIterator() {//使用DescendingKeyIterator。Set里面的遍历使用的是Iterator。从后往前遍历Key。 if (m instanceof TreeMap1) return ((TreeMap1<E, ?>) m).descendingKeyIterator(); else return ((NavigableSubMap<E, ?>) m).descendingKeyIterator(); } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean contains(Object o) { return m.containsKey(o); } public void clear() { m.clear(); } public E lower(E e) { return m.lowerKey(e); } public E floor(E e) { return m.floorKey(e); } public E ceiling(E e) { return m.ceilingKey(e); } public E higher(E e) { return m.higherKey(e); } public E first() { return m.firstKey(); } public E last() { return m.lastKey(); } public Comparator<? super E> comparator() { return m.comparator(); } public E pollFirst() { Map.Entry<E, ?> e = m.pollFirstEntry(); return (e == null) ? null : e.getKey(); } public E pollLast() { Map.Entry<E, ?> e = m.pollLastEntry(); return (e == null) ? null : e.getKey(); } public boolean remove(Object o) { int oldSize = size(); m.remove(o); return size() != oldSize; } //子KeySet。subMap,headMap,tailMap在TreeMap和NavigableSubMap和AscendingSubMap和DescendingSubMap都有。 //TreeMap的subMap返回AscendingSubMap,NavigableSubMap的subMap继续调用子类的subMap。 //AscendingSubMap的subMap返回AscendingSubMap,DescendingSubMap的subMap返回DescendingSubMap。 public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new KeySet<>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new KeySet<>(m.headMap(toElement, inclusive)); } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new KeySet<>(m.tailMap(fromElement, inclusive)); } public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } public NavigableSet<E> descendingSet() { return new KeySet<>(m.descendingMap()); } public Spliterator<E> spliterator() {//key分割器 return keySpliteratorFor(m); } } abstract class PrivateEntryIterator<T> implements Iterator<T> {//Iterator遍历器的基类 Entry<K, V> next; Entry<K, V> lastReturned; int expectedModCount; PrivateEntryIterator(Entry<K, V> first) { expectedModCount = modCount; lastReturned = null; next = first; } public boolean hasNext() {//final方法不能被重写 return next != null; } final Entry<K, V> nextEntry() {//后面的Entry Entry<K, V> e = next; if (e == null) throw new NoSuchElementException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); next = successor(e); lastReturned = e; return e; } final Entry<K, V> prevEntry() {//前面的Entry Entry<K, V> e = next; if (e == null) throw new NoSuchElementException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); next = predecessor(e); lastReturned = e; return e; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.left != null && lastReturned.right != null) next = lastReturned; deleteEntry(lastReturned); expectedModCount = modCount; lastReturned = null; } } final class EntryIterator extends PrivateEntryIterator<Map.Entry<K, V>> {//Entry遍历器Iterator EntryIterator(Entry<K, V> first) { super(first); } public Map.Entry<K, V> next() {//后面的Entry return nextEntry(); } } final class ValueIterator extends PrivateEntryIterator<V> {//Value遍历器Iterator ValueIterator(Entry<K, V> first) { super(first); } int i=5; // public final boolean hasNext() { // return i-- > 0 ;//next != null; // } public V next() {//后面的value return nextEntry().value; //(V) new Integer(888999); } } final class KeyIterator extends PrivateEntryIterator<K> {//Key遍历器Iterator KeyIterator(Entry<K, V> first) { super(first); } public K next() {//后面的key return nextEntry().key; } } final class DescendingKeyIterator extends PrivateEntryIterator<K> { DescendingKeyIterator(Entry<K, V> first) { super(first); } public K next() {//前面的key return prevEntry().key; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); deleteEntry(lastReturned); lastReturned = null; expectedModCount = modCount; } } Iterator<K> keyIterator() {//从前往后遍历key return new KeyIterator(getFirstEntry()); } Iterator<K> descendingKeyIterator() {//从后往前遍历key return new DescendingKeyIterator(getLastEntry()); } //---------------------------Set------Iterator--------------------------------------------------------- //---------------------------子Map也有keySet和EntrySet以及Entry和Key的迭代器和分割器,子Map还有subMap方法-------------- private static final Object UNBOUNDED = new Object();//边界 public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet();//new KeySet<>(DescendingSubMap.this) } public NavigableMap<K, V> descendingMap() {//降序子Map NavigableMap<K, V> km = descendingMap; return (km != null) ? km : (descendingMap = new DescendingSubMap<>(this, true, null, true, true, null, true)); } //升序子Map:AscendingSubMap。范围是从fromKey 到 toKey;fromInclusive是是否包含fromKey的标记,toInclusive是是否包含toKey的标记 public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return new AscendingSubMap<>(this, false, fromKey, fromInclusive, false, toKey, toInclusive); } // 范围从第一个节点 到 toKey, inclusive是是否包含toKey的标记 public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return new AscendingSubMap<>(this, true, null, true, false, toKey, inclusive); } // 范围是从 fromKey 到 最后一个节点,inclusive是是否包含fromKey的标记 public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return new AscendingSubMap<>(this, false, fromKey, inclusive, true, null, true); } // 范围是从fromKey(包括) 到 toKey(不包括) public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } // 范围从第一个节点 到 toKey(不包括) public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } // 范围是从 fromKey(包括) 到 最后一个节点 public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } //NavigableSubMap里面有TreeMap1这个m。m只能是TreeMap1不是TreeMap1的子Map。KeySet里面也有m,这个m可以是TreeMap1也可以是TreeMap1的子Map abstract static class NavigableSubMap<K, V> extends AbstractMap1<K, V> implements NavigableMap<K, V>, Serializable { private static final long serialVersionUID = -2102997345730753016L; final TreeMap1<K, V> m; // fromStart=true从map第一个位置开始. toEnd=true就一直到map的最后。 fromStart为true,lo,loInclusive就失效。toEnd为true,hi,hiInclusive就失效。 final boolean fromStart, toEnd; final K lo, hi; final boolean loInclusive, hiInclusive;//loInclusive=true就包括lo,hiInclusive=true就包括hi。 NavigableSubMap(TreeMap1<K, V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi,boolean hiInclusive) { if (!fromStart && !toEnd) {//fromStart=toEnd=fasle,lo和hi就不能为null if (m.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); } else { if (!fromStart) // fromStart=fasle,就要有lo不能为null m.compare(lo, lo); if (!toEnd)//toEnd=fasle,就要有hi不能为null m.compare(hi, hi); } this.m = m; this.fromStart = fromStart; this.lo = lo; this.loInclusive = loInclusive; this.toEnd = toEnd; this.hi = hi; this.hiInclusive = hiInclusive; } //fromStart为true或者toEnd为true就不会超一边的标。 final boolean tooLow(Object key) {//太小 if (!fromStart) { int c = m.compare(key, lo);//key<lo就超标,key=lo但是不包括lo就超标。 if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } final boolean tooHigh(Object key) {//太大 if (!toEnd) { int c = m.compare(key, hi);//key>hi就超标,key=hi但是不包括hi就超标。 if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } final boolean inRange(Object key) {//key是否超标。等于两边端点时候考虑loInclusive和hiInclusive。 return !tooLow(key) && !tooHigh(key); } //fromStart为true或者toEnd为true就不会超一边的标。 final boolean inClosedRange(Object key) {//等于2边端点不超标。 return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0); } final boolean inRange(Object key, boolean inclusive) {//inclusive为true,等于两边端点时候考虑loInclusive和hiInclusive。 //inclusive为false,等于2边端点时候不超标。 return inclusive ? inRange(key) : inClosedRange(key); } final TreeMap1.Entry<K, V> absLowest() {//真正最小元素 TreeMap1.Entry<K, V> e = (fromStart ? m.getFirstEntry()//从开头开始就是第一个元素 //不从开头开始。 包括lo,找lo最近的大,可以等于lo。不包括lo,找lo最近的大,不可以等于lo。 : (loInclusive ? m.getCeilingEntry(lo) : m.getHigherEntry(lo))); return (e == null || tooHigh(e.key)) ? null : e; } final TreeMap1.Entry<K, V> absHighest() {//真正最大元素 TreeMap1.Entry<K, V> e = (toEnd ? m.getLastEntry() //hi最近的小,可以相等, hi最近的小,不可以相等 : (hiInclusive ? m.getFloorEntry(hi) : m.getLowerEntry(hi))); return (e == null || tooLow(e.key)) ? null : e; } final TreeMap1.Entry<K, V> absCeiling(K key) {// key最近的大,可以相等 if (tooLow(key)) return absLowest(); TreeMap1.Entry<K, V> e = m.getCeilingEntry(key);// key最近的大,可以相等 return (e == null || tooHigh(e.key)) ? null : e; } final TreeMap1.Entry<K, V> absHigher(K key) {// key最近的大,不可以相等 if (tooLow(key)) return absLowest(); TreeMap1.Entry<K, V> e = m.getHigherEntry(key); return (e == null || tooHigh(e.key)) ? null : e; } final TreeMap1.Entry<K, V> absFloor(K key) {// 最近的小,可以相等 if (tooHigh(key)) return absHighest(); TreeMap1.Entry<K, V> e = m.getFloorEntry(key);// 最近的小,可以相等 return (e == null || tooLow(e.key)) ? null : e; } final TreeMap1.Entry<K, V> absLower(K key) {// 最近的小,不可以相等。 if (tooHigh(key)) return absHighest(); TreeMap1.Entry<K, V> e = m.getLowerEntry(key);// 最近的小,不可以相等。 return (e == null || tooLow(e.key)) ? null : e; } final TreeMap1.Entry<K, V> absHighFence() {//最高界限 //hi最近的大,不可以相等。 hi最近的大,可以相等 return (toEnd ? null : (hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi))); } final TreeMap1.Entry<K, V> absLowFence() {//遍历时候最低界限 //lo最近的小,不能相等。 lo最近的小,可以相等。 return (fromStart ? null : (loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo))); } abstract TreeMap1.Entry<K, V> subLowest(); abstract TreeMap1.Entry<K, V> subHighest(); abstract TreeMap1.Entry<K, V> subCeiling(K key); abstract TreeMap1.Entry<K, V> subHigher(K key); abstract TreeMap1.Entry<K, V> subFloor(K key); abstract TreeMap1.Entry<K, V> subLower(K key); abstract Iterator<K> keyIterator();//升序迭代器 abstract Spliterator<K> keySpliterator(); abstract Iterator<K> descendingKeyIterator();//递减迭代器 public boolean isEmpty() { return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty(); } public int size() { return (fromStart && toEnd) ? m.size() : entrySet().size(); } public final boolean containsKey(Object key) { return inRange(key) && m.containsKey(key); } public final V put(K key, V value) { if (!inRange(key)) throw new IllegalArgumentException("key out of range"); return m.put(key, value); } public final V get(Object key) { return !inRange(key) ? null : m.get(key); } public final V remove(Object key) { return !inRange(key) ? null : m.remove(key); } public final Entry<K, V> ceilingEntry(K key) { return exportEntry(subCeiling(key)); } public final K ceilingKey(K key) { return keyOrNull(subCeiling(key)); } public final Entry<K, V> higherEntry(K key) { return exportEntry(subHigher(key)); } public final K higherKey(K key) { return keyOrNull(subHigher(key)); } public final Entry<K, V> floorEntry(K key) { return exportEntry(subFloor(key)); } public final K floorKey(K key) { return keyOrNull(subFloor(key)); } public final Entry<K, V> lowerEntry(K key) { return exportEntry(subLower(key)); } public final K lowerKey(K key) { return keyOrNull(subLower(key)); } public final K firstKey() { return key(subLowest()); } public final K lastKey() { return key(subHighest()); } public final Entry<K, V> firstEntry() { return exportEntry(subLowest()); } public final Entry<K, V> lastEntry() { return exportEntry(subHighest()); } public final Entry<K, V> pollFirstEntry() { TreeMap1.Entry<K, V> e = subLowest(); Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } public final Entry<K, V> pollLastEntry() { TreeMap1.Entry<K, V> e = subHighest(); Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } public final NavigableSet<K> navigableKeySet() { KeySet<K> nksv = navigableKeySetView; return (nksv != null) ? nksv : (navigableKeySetView = new KeySet<>(this)); } public final Set<K> keySet() { return navigableKeySet(); } public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } public final SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } public final SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } public final SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } // Views transient NavigableMap<K, V> descendingMapView;//接口NavigableMap transient EntrySetView entrySetView;//内部类EntrySetView transient KeySet<K> navigableKeySetView;//外部KeySet // 子Map的Entry集合的操作, abstract class EntrySetView extends AbstractSet<Entry<K, V>> { private transient int size = -1, sizeModCount; public int size() { if (fromStart && toEnd)//从开始到结束 return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator<?> i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } public boolean isEmpty() { TreeMap1.Entry<K, V> n = absLowest();//外部类NavigableSubMap的方法。内部类直接使用外部类的方法。 return n == null || tooHigh(n.key); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Entry<?, ?> entry = (Entry<?, ?>) o; Object key = entry.getKey(); if (!inRange(key)) return false; TreeMap1.Entry<?, ?> node = m.getEntry(key); return node != null && valEquals(node.getValue(), entry.getValue()); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Entry<?, ?> entry = (Entry<?, ?>) o; Object key = entry.getKey(); if (!inRange(key)) return false; TreeMap1.Entry<K, V> node = m.getEntry(key); if (node != null && valEquals(node.getValue(), entry.getValue())) { m.deleteEntry(node); return true; } return false; } } // 子Map迭代器公共类 abstract class SubMapIterator<T> implements Iterator<T> { TreeMap1.Entry<K, V> lastReturned; TreeMap1.Entry<K, V> next; final Object fenceKey; int expectedModCount; //开始和结束位置 SubMapIterator(TreeMap1.Entry<K, V> first, TreeMap1.Entry<K, V> fence) { expectedModCount = m.modCount; lastReturned = null; next = first; fenceKey = fence == null ? UNBOUNDED : fence.key; } public final boolean hasNext() { return next != null && next.key != fenceKey;//栅栏 } final TreeMap1.Entry<K, V> nextEntry() {//后面一个元素 TreeMap1.Entry<K, V> e = next; if (e == null || e.key == fenceKey) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next = successor(e); lastReturned = e; return e; } final TreeMap1.Entry<K, V> prevEntry() {//前面一个元素 TreeMap1.Entry<K, V> e = next; if (e == null || e.key == fenceKey) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next = predecessor(e); lastReturned = e; return e; } final void removeAscending() {//升序删除 if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.left != null && lastReturned.right != null) next = lastReturned; m.deleteEntry(lastReturned); lastReturned = null; expectedModCount = m.modCount; } final void removeDescending() {//降序删除 if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); m.deleteEntry(lastReturned); lastReturned = null; expectedModCount = m.modCount; } } // 子Map升序Entry迭代器 final class SubMapEntryIterator extends SubMapIterator<Entry<K, V>> { SubMapEntryIterator(TreeMap1.Entry<K, V> first, TreeMap1.Entry<K, V> fence) { super(first, fence); } public Entry<K, V> next() {//后面一个元素 return nextEntry(); } public void remove() {//升序删除 removeAscending(); } } // 子Map降序Entry迭代器 final class DescendingSubMapEntryIterator extends SubMapIterator<Entry<K, V>> { DescendingSubMapEntryIterator(TreeMap1.Entry<K, V> last, TreeMap1.Entry<K, V> fence) { super(last, fence); } public Entry<K, V> next() {//前面一个元素 return prevEntry(); } public void remove() {//降序删除 removeDescending(); } } // 子Map升序Key迭代器和分割器 final class SubMapKeyIterator extends SubMapIterator<K> implements Spliterator<K> { SubMapKeyIterator(TreeMap1.Entry<K, V> first, TreeMap1.Entry<K, V> fence) { super(first, fence); } public K next() {//后一个key return nextEntry().key; } public void remove() {//升序删除 removeAscending(); } //分割 public Spliterator<K> trySplit() { return null; } public void forEachRemaining(Consumer<? super K> action) { while (hasNext()) action.accept(next());//遍历所有元素 } public boolean tryAdvance(Consumer<? super K> action) { if (hasNext()) { action.accept(next());//遍历所有元素 return true; } return false; } public long estimateSize() { return Long.MAX_VALUE; } public int characteristics() { return Spliterator.DISTINCT | Spliterator.ORDERED | Spliterator.SORTED; } public final Comparator<? super K> getComparator() { return NavigableSubMap.this.comparator(); } } // 子Map降序Key迭代器和分割器 final class DescendingSubMapKeyIterator extends SubMapIterator<K> implements Spliterator<K> { DescendingSubMapKeyIterator(TreeMap1.Entry<K, V> last, TreeMap1.Entry<K, V> fence) { super(last, fence); } public K next() {//前一个key return prevEntry().key; } public void remove() {//降序删除 removeDescending(); } //分割 public Spliterator<K> trySplit() { return null; } public void forEachRemaining(Consumer<? super K> action) { while (hasNext()) action.accept(next());//遍历所有元素 } public boolean tryAdvance(Consumer<? super K> action) { if (hasNext()) { action.accept(next());//遍历所有元素 return true; } return false; } public long estimateSize() { return Long.MAX_VALUE; } public int characteristics() { return Spliterator.DISTINCT | Spliterator.ORDERED; } } } //上面是父类的内部类Iterator迭代器,这里是父类的升序子Map. static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866124060L; AscendingSubMap(TreeMap1<K, V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi,boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return m.comparator(); } public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<>(m, false, fromKey, fromInclusive, false, toKey, toInclusive); } public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {//包括前面不包括后面 if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<>(m, fromStart, lo, loInclusive, false, toKey, inclusive); } public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {//包括后面不包括前面 if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new AscendingSubMap<>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive); } public NavigableMap<K, V> descendingMap() { NavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv//降序子Map : (descendingMapView = new DescendingSubMap<>(m, fromStart, lo, loInclusive, toEnd, hi,hiInclusive)); } Iterator<K> keyIterator() {//使用父类内部类SubMapKeyIterator迭代器 return new SubMapKeyIterator(absLowest(), absHighFence()); } Spliterator<K> keySpliterator() {//使用父类内部类SubMapKeyIterator迭代器 return new SubMapKeyIterator(absLowest(), absHighFence()); } Iterator<K> descendingKeyIterator() {//使用父类内部类DescendingSubMapKeyIterator迭代器 return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } final class AscendingEntrySetView extends EntrySetView { public Iterator<Entry<K, V>> iterator() { return new SubMapEntryIterator(absLowest(), absHighFence()); } } public Set<Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : (entrySetView = new AscendingEntrySetView()); } TreeMap1.Entry<K, V> subLowest() { return absLowest(); } TreeMap1.Entry<K, V> subHighest() { return absHighest(); } TreeMap1.Entry<K, V> subCeiling(K key) { return absCeiling(key); } TreeMap1.Entry<K, V> subHigher(K key) { return absHigher(key); } TreeMap1.Entry<K, V> subFloor(K key) { return absFloor(key); } TreeMap1.Entry<K, V> subLower(K key) { return absLower(key); } } //降序子Map static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866120460L; DescendingSubMap(TreeMap1<K, V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator); public Comparator<? super K> comparator() { return reverseComparator; } public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<>(m, false, toKey, toInclusive, false, fromKey, fromInclusive); } public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<>(m, false, toKey, inclusive, toEnd, hi, hiInclusive); } public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new DescendingSubMap<>(m, fromStart, lo, loInclusive, false, fromKey, inclusive); } public NavigableMap<K, V> descendingMap() { NavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } Iterator<K> keyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } Spliterator<K> keySpliterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } Iterator<K> descendingKeyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } final class DescendingEntrySetView extends EntrySetView { public Iterator<Entry<K, V>> iterator() { return new DescendingSubMapEntryIterator(absHighest(), absLowFence()); } } public Set<Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : (entrySetView = new DescendingEntrySetView()); } TreeMap1.Entry<K, V> subLowest() { return absHighest(); } TreeMap1.Entry<K, V> subHighest() { return absLowest(); } TreeMap1.Entry<K, V> subCeiling(K key) { return absFloor(key); } TreeMap1.Entry<K, V> subHigher(K key) { return absLower(key); } TreeMap1.Entry<K, V> subFloor(K key) { return absCeiling(key); } TreeMap1.Entry<K, V> subLower(K key) { return absHigher(key); } } //---------------------------子Map------------------------------------------------------- //---------------------------分割器------------------------------------------------------- //DescendingSubMap的keySpliterator()返回DescendingSubMapKeyIterator //AscendingSubMap的 keySpliterator()返回SubMapKeyIterator //NavigableSubMap的abstract keySpliterator() //TreeMap1的keySpliterator()返回KeySpliterator,TreeMap1的descendingKeySpliterator()返回DescendingKeySpliterator public static <K> Spliterator<K> keySpliteratorFor(NavigableMap<K, ?> m) {//key分割器,keySet的分割器方法。 if (m instanceof TreeMap1) { TreeMap1<K, Object> t = (TreeMap1<K, Object>) m; return t.keySpliterator();//返回KeySpliterator } if (m instanceof DescendingSubMap) { DescendingSubMap<K, ?> dm = (DescendingSubMap<K, ?>) m; TreeMap1<K, ?> tm = dm.m; if (dm == tm.descendingMap) { TreeMap1<K, Object> t = (TreeMap1<K, Object>) tm; return t.descendingKeySpliterator();//降序key分割器,DescendingKeySpliterator } } //AscendingSubMap NavigableSubMap<K, ?> sm = (NavigableSubMap<K, ?>) m; return sm.keySpliterator();//返回SubMapKeyIterator } public final Spliterator<K> keySpliterator() {//TreeMap1的方法,keySet的分割器方法。 return new KeySpliterator<K, V>(this, null, null, 0, -1, 0); } public final Spliterator<K> descendingKeySpliterator() {//TreeMap1的方法 return new DescendingKeySpliterator<K, V>(this, null, null, 0, -2, 0); } static class TreeMapSpliterator<K, V> { final TreeMap1<K, V> tree; Entry<K, V> current; // traverser; initially first node in range Entry<K, V> fence; // one past last, or null int side; // 0: top, -1: is a left split, +1: right int est; // tree.size,尺寸估算(仅适用于顶层) int expectedModCount; // for CME checks TreeMapSpliterator(TreeMap1<K, V> tree, Entry<K, V> origin, Entry<K, V> fence, int side, int est,int expectedModCount) { this.tree = tree; this.current = origin; this.fence = fence; this.side = side; this.est = est; this.expectedModCount = expectedModCount; } final int getEstimate() { // 初始化:est=-1,current=第一个元素,est=size。est=-2,current=最后一个元素,est=size。 int s; TreeMap1<K, V> t; if ((s = est) < 0) {//est初始化是-1或者-2,大于0就说明已经初始化。 if ((t = tree) != null) {//est=-1,-1升序, -2降序。 current = (s == -1) ? t.getFirstEntry() : t.getLastEntry(); s = est = t.size;//然后est=size, expectedModCount = t.modCount; } else s = est = 0; } return s;//返回TreeMap1.size } public final long estimateSize() { return (long) getEstimate(); } } static final class KeySpliterator<K, V> extends TreeMapSpliterator<K, V> implements Spliterator<K> { KeySpliterator(TreeMap1<K, V> tree, Entry<K, V> origin, Entry<K, V> fence, int side, int est,int expectedModCount) { super(tree, origin, fence, side, est, expectedModCount);//this, null, null(开始结束null), 0, -1, 0 } //trySplit()才会计算fence,forEachRemaining()不计算fence为null,一直到末尾。 public KeySpliterator<K, V> trySplit() { if (est < 0) getEstimate(); //没有初始化就初始化:current,est,expectedModCount int d = side; //计算s这个fence,截取出去之后current=fence, Entry<K, V> e = current, f = fence, s = ((e == null || e == f) ? null : // current=null或者current=fence,s就是null。 (d == 0) ? tree.root : // side=0,s=root (d > 0) ? e.right : // side>0,s=current.right (d < 0 && f != null) ? f.left : // side<0,fence!= null,s=fence.left null);// side<0,fence=null,s=null if (s != null && s != e && s != f && tree.compare(e.key, s.key) < 0) { // e是开始位置,s是结束位置。 side = 1;//side=1留下来'根'的右边 return new KeySpliterator<>(tree, e, current = s, -1, est >>>= 1, expectedModCount);//side=-1出去的是‘根’的左边的。 } return null; }//每次分割以root作为边界,出去root左边的留下来root右边的。子Spliterator分割也是以他的root作为界限分割的。 public void forEachRemaining(Consumer<? super K> action) { if (action == null) throw new NullPointerException(); if (est < 0) getEstimate(); // 没有调用trySplit()方法 Entry<K, V> f = fence, e, p, pl; if ((e = current) != null && e != f) {//current!=fence current = f; // 用完,再次调用forEachRemaining就不执行。 do { action.accept(e.key); //找后继 if ((p = e.right) != null) { while ((pl = p.left) != null) p = pl; } else { while ((p = e.parent) != null && e == p.right)//left关系退出 e = p; } } while ((e = p) != null && e != f);//等于栅栏退出 if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super K> action) { Entry<K, V> e; if (action == null) throw new NullPointerException(); if (est < 0) getEstimate(); if ((e = current) == null || e == fence)//current=null或者current=fence, return false; current = successor(e);//后继 action.accept(e.key); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } public int characteristics() { return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED; } public final Comparator<? super K> getComparator() { return tree.comparator; } } static final class DescendingKeySpliterator<K, V> extends TreeMapSpliterator<K, V> implements Spliterator<K> { DescendingKeySpliterator(TreeMap1<K, V> tree, Entry<K, V> origin, Entry<K, V> fence, int side, int est, int expectedModCount) {//this, null, null, 0, -2, 0 super(tree, origin, fence, side, est, expectedModCount); } public DescendingKeySpliterator<K, V> trySplit() { if (est < 0) getEstimate(); // force initialization int d = side; Entry<K, V> e = current, f = fence, s = ((e == null || e == f) ? null : // empty (d == 0) ? tree.root : // was top (d < 0) ? e.left : // was left (d > 0 && f != null) ? f.right : // was right null); if (s != null && s != e && s != f && tree.compare(e.key, s.key) > 0) { // e not already past s side = 1; return new DescendingKeySpliterator<>(tree, e, current = s, -1, est >>>= 1, expectedModCount); } return null; } public void forEachRemaining(Consumer<? super K> action) { if (action == null) throw new NullPointerException(); if (est < 0) getEstimate(); // force initialization Entry<K, V> f = fence, e, p, pr; if ((e = current) != null && e != f) { current = f; // exhaust do { action.accept(e.key); if ((p = e.left) != null) { while ((pr = p.right) != null) p = pr; } else { while ((p = e.parent) != null && e == p.left) e = p; } } while ((e = p) != null && e != f); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super K> action) { Entry<K, V> e; if (action == null) throw new NullPointerException(); if (est < 0) getEstimate(); // force initialization if ((e = current) == null || e == fence) return false; current = predecessor(e); action.accept(e.key); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } public int characteristics() { return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.DISTINCT | Spliterator.ORDERED; } } static final class ValueSpliterator<K, V> extends TreeMapSpliterator<K, V> implements Spliterator<V> { ValueSpliterator(TreeMap1<K, V> tree, Entry<K, V> origin, Entry<K, V> fence, int side, int est, int expectedModCount) {//this, null, null, 0, -1, 0 super(tree, origin, fence, side, est, expectedModCount); } public ValueSpliterator<K, V> trySplit() { if (est < 0) getEstimate(); // force initialization int d = side; Entry<K, V> e = current, f = fence, s = ((e == null || e == f) ? null : // empty (d == 0) ? tree.root : // was top (d > 0) ? e.right : // was right (d < 0 && f != null) ? f.left : // was left null); if (s != null && s != e && s != f && tree.compare(e.key, s.key) < 0) { // e not already past s side = 1; return new ValueSpliterator<>(tree, e, current = s, -1, est >>>= 1, expectedModCount); } return null; } public void forEachRemaining(Consumer<? super V> action) { if (action == null) throw new NullPointerException(); if (est < 0) getEstimate(); // force initialization Entry<K, V> f = fence, e, p, pl; if ((e = current) != null && e != f) { current = f; // exhaust do { action.accept(e.value); if ((p = e.right) != null) { while ((pl = p.left) != null) p = pl; } else { while ((p = e.parent) != null && e == p.right) e = p; } } while ((e = p) != null && e != f); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super V> action) { Entry<K, V> e; if (action == null) throw new NullPointerException(); if (est < 0) getEstimate(); // force initialization if ((e = current) == null || e == fence) return false; current = successor(e); action.accept(e.value); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } public int characteristics() { return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.ORDERED; } } static final class EntrySpliterator<K, V> extends TreeMapSpliterator<K, V> implements Spliterator<Map.Entry<K, V>> { EntrySpliterator(TreeMap1<K, V> tree, Entry<K, V> origin, Entry<K, V> fence, int side, int est, int expectedModCount) { super(tree, origin, fence, side, est, expectedModCount); } public EntrySpliterator<K, V> trySplit() { if (est < 0) getEstimate(); // force initialization int d = side; Entry<K, V> e = current, f = fence, s = ((e == null || e == f) ? null : // empty (d == 0) ? tree.root : // was top (d > 0) ? e.right : // was right (d < 0 && f != null) ? f.left : // was left null); if (s != null && s != e && s != f && tree.compare(e.key, s.key) < 0) { // e not already past s side = 1; return new EntrySpliterator<>(tree, e, current = s, -1, est >>>= 1, expectedModCount); } return null; } public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) { if (action == null) throw new NullPointerException(); if (est < 0) getEstimate(); // force initialization Entry<K, V> f = fence, e, p, pl; if ((e = current) != null && e != f) { current = f; // exhaust do { action.accept(e); if ((p = e.right) != null) { while ((pl = p.left) != null) p = pl; } else { while ((p = e.parent) != null && e == p.right) e = p; } } while ((e = p) != null && e != f); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super Map.Entry<K, V>> action) { Entry<K, V> e; if (action == null) throw new NullPointerException(); if (est < 0) getEstimate(); // force initialization if ((e = current) == null || e == fence) return false; current = successor(e); action.accept(e); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } public int characteristics() { return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED; } @Override public Comparator<Map.Entry<K, V>> getComparator() { // Adapt or create a key-based comparator if (tree.comparator != null) { return Map.Entry.comparingByKey(tree.comparator); } else { return (Comparator<Map.Entry<K, V>> & Serializable) (e1, e2) -> { Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey(); return k1.compareTo(e2.getKey()); }; } } } //---------------------------分割器------------------------------------------------------- }
package map;public abstract class AbstractMap1<K,V> implements Map<K,V> { protected AbstractMap1() { } public int size() { return entrySet().size();//entrySet()抽象方法 } public boolean isEmpty() { return size() == 0; } public boolean containsValue(Object value) { Iterator<Entry<K,V>> i = entrySet().iterator();//entrySet()抽象方法 if (value==null) {//containsValue value为null的。 while (i.hasNext()) { Entry<K,V> e = i.next(); if (e.getValue()==null) return true; } } else { while (i.hasNext()) { Entry<K,V> e = i.next(); if (value.equals(e.getValue())) return true; } } return false; } public boolean containsKey(Object key) { Iterator<Map.Entry<K,V>> i = entrySet().iterator(); if (key==null) {//containsKey key为null的。 while (i.hasNext()) { Entry<K,V> e = i.next(); if (e.getKey()==null) return true; } } else { while (i.hasNext()) { Entry<K,V> e = i.next(); if (key.equals(e.getKey())) return true; } } return false; } public V get(Object key) { Iterator<Entry<K,V>> i = entrySet().iterator(); if (key==null) {//get key为null的。 while (i.hasNext()) { Entry<K,V> e = i.next(); if (e.getKey()==null) return e.getValue(); } } else { while (i.hasNext()) { Entry<K,V> e = i.next(); if (key.equals(e.getKey())) return e.getValue(); } } return null; } public V put(K key, V value) {//子类实现 throw new UnsupportedOperationException(); } public V remove(Object key) { Iterator<Entry<K,V>> i = entrySet().iterator(); Entry<K,V> correctEntry = null; if (key==null) {//remove key为null的。 while (correctEntry==null && i.hasNext()) { Entry<K,V> e = i.next(); if (e.getKey()==null) correctEntry = e; } } else { while (correctEntry==null && i.hasNext()) { Entry<K,V> e = i.next(); if (key.equals(e.getKey())) correctEntry = e; } } V oldValue = null; if (correctEntry !=null) { oldValue = correctEntry.getValue(); i.remove(); } return oldValue; } public void putAll(Map<? extends K, ? extends V> m) { Set<?> s = m.entrySet(); for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue());//TreeMap调用过来的,这里调用TreeMap的put方法,不调用本类的put方法。 } public void clear() { entrySet().clear(); } public abstract Set<Entry<K,V>> entrySet();//Entry的集合 public transient Set<K> keySet; public transient Collection<V> values; public Set<K> keySet() { Set<K> ks = keySet; if (ks == null) { ks = new AbstractSet<K>() {//集合的值是根据iterator()返回的Iterator对象的hasNext和next方法确定的。 public Iterator<K> iterator() { return new Iterator<K>() { private Iterator<Entry<K,V>> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public K next() { return i.next().getKey(); } public void remove() { i.remove(); } }; } public int size() {//大小方法 return AbstractMap1.this.size(); } public boolean isEmpty() { return AbstractMap1.this.isEmpty(); } public void clear() { AbstractMap1.this.clear(); } public boolean contains(Object k) {//包含方法 return AbstractMap1.this.containsKey(k); } }; keySet = ks; } return ks; } public Collection<V> values() { Collection<V> vals = values; if (vals == null) {//初始化values vals = new AbstractCollection<V>() {//集合的值是根据iterator()返回的Iterator对象的hasNext和next方法确定的。 public Iterator<V> iterator() { return new Iterator<V>() { private Iterator<Entry<K,V>> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public V next() { return i.next().getValue(); } public void remove() { i.remove(); } }; } public int size() { return AbstractMap1.this.size(); } public boolean isEmpty() { return AbstractMap1.this.isEmpty(); } public void clear() { AbstractMap1.this.clear(); } public boolean contains(Object v) { return AbstractMap1.this.containsValue(v); } }; values = vals; } return vals; } public boolean equals(Object o) {//2个map中每个元素是不是都相等 if (o == this) return true; if (!(o instanceof Map)) return false; Map<?,?> m = (Map<?,?>) o; if (m.size() != size()) return false; try { Iterator<Entry<K,V>> i = entrySet().iterator();//entrySet()返回EntrySet,iterator()返回EntryIterator。集合里面有遍历器。 while (i.hasNext()) {//hasNext是父类HashIterator的方法 Entry<K,V> e = i.next();//hasNext是父类HashIterator的方法 K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(m.get(key)==null && m.containsKey(key))) //m没有key return false; } else { if (!value.equals(m.get(key))) //value不为null,就看value是否相等。 return false; } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } public int hashCode() { int h = 0; Iterator<Entry<K,V>> i = entrySet().iterator(); while (i.hasNext()) h += i.next().hashCode(); return h; } public String toString() { Iterator<Entry<K,V>> i = entrySet().iterator();//entrySet()返回EntrySet,iterator()返回EntryIterator。集合里面有遍历器。 if (! i.hasNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append("{¥"); for (;;) { Entry<K,V> e = i.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (!i.hasNext()) return sb.append('}').toString(); sb.append(',').append(' '); } } protected Object clone() throws CloneNotSupportedException { AbstractMap1<?,?> result = (AbstractMap1<?,?>)super.clone();//native方法 result.keySet = null; result.values = null; return result; } private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } public static class SimpleEntry<K,V> implements Entry<K,V>, java.io.Serializable{//对外接口 private static final long serialVersionUID = -8499721149061103585L; private final K key; private V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry<? extends K, ? extends V> entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return eq(key, e.getKey()) && eq(value, e.getValue()); } public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { return key + "=#" + value; } } public static class SimpleImmutableEntry<K,V> implements Entry<K,V>, java.io.Serializable{//Entry的封装 private static final long serialVersionUID = 7138329143949025153L; private final K key; private final V value; public SimpleImmutableEntry(K key, V value) { this.key = key; this.value = value; } public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return eq(key, e.getKey()) && eq(value, e.getValue()); } public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { return key + "=*" + value; } } }