红黑树的应用----TreeMap

  • 红黑树是一种类似于平衡二叉树的结构
  • 特点 :
    • 根结点是黑的。
    • 每个节点非黑即红
    • 如果节点为红 那么其子节点肯定是黑色(注意 : 没有2个相邻的红节点)
    • 叶节点下面有2个null的黑色子节点
    • 从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java.io.Serializable{
    //比较器 : 用于维护其节点比较顺序  默认根据键值自然排序
    private final Comparator<? super K> comparator;
	//根节点
    private transient Entry<K,V> root;

    //集合长度
    private transient int size = 0;

    //集合被修改的次数
    private transient int modCount = 0;

    //创建一个空数映射  TreeMap中的元素按照自然排序进行排列。
    public TreeMap() {
        comparator = null;
    }

    //构造一个新的、空的树映射,该映射根据给定比较器进行排序
    public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

    //构造一个与给定映射具有相同映射关系的新的树映射,该映射根据其键的自然顺序 进行排序。
    public TreeMap(Map<? extends K, ? extends V> m) {
        comparator = null;
        putAll(m);
    }

    //构造一个与指定有序映射具有相同映射关系和相同排序顺序的新的树映射。此方法是以线性时间运行的。
    public TreeMap(SortedMap<K, ? extends V> m) {
        comparator = m.comparator();
        try {
			// 基于排序数据的线性时间树构建算法
            buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
        } catch (java.io.IOException cannotHappen) {
        } catch (ClassNotFoundException cannotHappen) {
        }
    }


    // Query Operations

    //返回集合长度
    public int size() {
        return size;
    }

    //判断集合是否存在该key值
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }

    //判断集合是否存在指定value值
    public boolean containsValue(Object value) {
        for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
            if (valEquals(value, e.value))
                return true;
        return false;
    }

    //根据key返回指定的value值
    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() {
        return key(getFirstEntry());
    }

    //返回当前集合最后一个键
    public K lastKey() {
        return key(getLastEntry());
    }

    // 将map中的全部节点添加到TreeMap中
    public void putAll(Map<? extends K, ? extends V> map) {
        int mapSize = map.size();
		// 如果TreeMap的大小是0,且map的大小不是0,且map是已排序的“key-value对”
        if (size==0 && mapSize!=0 && map instanceof SortedMap) {
            Comparator<?> c = ((SortedMap<?,?>)map).comparator();
			// 如果TreeMap和map的比较器相等;
            // 则将map的元素全部拷贝到TreeMap中,然后返回!
            if (c == comparator || (c != null && c.equals(comparator))) {
                ++modCount;
                try {
                    buildFromSorted(mapSize, map.entrySet().iterator(),null, null);
                } catch (java.io.IOException cannotHappen) {
                } catch (ClassNotFoundException cannotHappen) {
                }
                return;
            }
        }
		// 调用AbstractMap中的putAll();
        // AbstractMap中的putAll()又会调用到TreeMap的put()
        super.putAll(map);
    }

    // 获取TreeMap中“键”为key的节点
    final Entry<K,V> getEntry(Object key) {
        //  若 比较器 为null,则通过getEntryUsingComparator()获取“键”为key的节点
        if (comparator != null)
            return getEntryUsingComparator(key);
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;
        Entry<K,V> p = root;//把p设置为根节点
        while (p != null) {
			/**
			 * 1. 比较者(调用方法的k) > 被比较者(方法参数 p.key) 返回 1
			 * 2. 比较者(调用方法的k) = 被比较者(方法参数 p.key) 返回 0
			 * 3. 比较者(调用方法的k) < 被比较者(方法参数 p.key) 返回 -1
			 */
            int cmp = k.compareTo(p.key);
            if (cmp < 0)//当根节点的key值大于key  则查询左子树
                p = p.left;
            else if (cmp > 0)//根节点小于key  查询右子树
                p = p.right;
            else//否则等于 就返回当前值
                return p;
        }
        return null;
    }

    // 获取TreeMap中“键”为key的节点(对应TreeMap的比较器不是null的情况 自定义排序)
    final Entry<K,V> getEntryUsingComparator(Object key) {
        @SuppressWarnings("unchecked")
            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)//当根节点的key值大于key  则查询左子树
                    p = p.left;
                else if (cmp > 0)//根节点小于key  查询右子树
                    p = p.right;
                else//否则等于 就返回当前值
                    return p;
            }
        }
        return null;
    }

    //获取TreeMap中 >=key值的最小节点  不存在返回null
    final Entry<K,V> getCeilingEntry(K key) {
        Entry<K,V> p = root;//令p为根节点
        while (p != null) {//当p不为空
            int cmp = compare(key, p.key);//判断比较器不为空时使用compare()方法 为空使用compareTo()方法
            if (cmp < 0) {//当根节点大于key值
                if (p.left != null)//且根节点左子树不为空 继续查询左子树
                    p = p.left;
                else//直到节点左子树为空时 返回当前节点
                    return p;
            } else if (cmp > 0) {//根节点小于key
                if (p.right != null) {//且右子树不为空 继续查询
                    p = p.right;
                } else {//直到节点右子树为空时 有2种情况 1. key值大于集合的所有节点 返回null  2. 返回集合里>=key的最小节点值
                    Entry<K,V> parent = p.parent;
                    Entry<K,V> ch = p;
					//
                    while (parent != null && ch == parent.right) {
                        ch = parent;
                        parent = parent.parent;
                    }
                    return parent;
                }
            } else
                return p;//如果等于根节点 则返回该节点   
        }
        return null;
    }

    //获取TreeMap中 <=key的最大的节点;
    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;
    }

    //获取TreeMap中 >key值的最小节点
    final Entry<K,V> getHigherEntry(K 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 {
                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;
    }

    //获取TreeMap中 <key的最大的节点
    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;
    }

    //添加方法 注意treemap使用的是红黑数(类似于一个平衡二叉树)
	//这里会优先根据key值查找集合是否存在 存在就覆盖并返回新值 不存在会新建节点 添加该值
    public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {//当红黑树为空 则插入根节点
            compare(key, key); // 检查可能为空

            root = new Entry<>(key, value, null);//创建为根节点
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {//当比较器不为空  根据自定义排序方法查找节点
			//在t不为空时 根据key进行查询对应节点 (注意 集合是根据key值进行排序的)
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)//如果key小于当前节点 查询左子树
                    t = t.left;
                else if (cmp > 0)//大于当前节点查询右子树
                    t = t.right;
                else
                    return t.setValue(value);//当key值相等时会覆盖当前值 并返回新值
            } while (t != null);//当子节点不为空时进行查找
        }
        else {//否则根据默认的排序方法进行排序查找
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key;
            do {
                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);
        }
		//单key值在集合里不存在时(此时的parent只有一个或没有子节点) 会新建节点添加到该节点的子节点里
        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() {
        TreeMap<?,?> clone;
        try {
            clone = (TreeMap<?,?>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }

        // Put clone into "virgin" state (except for comparator)
        clone.root = null;
        clone.size = 0;
        clone.modCount = 0;
        clone.entrySet = null;
        clone.navigableKeySet = null;
        clone.descendingMap = null;

        // Initialize clone with our mappings
        try {
            clone.buildFromSorted(size, entrySet().iterator(), null, null);
        } catch (java.io.IOException cannotHappen) {
        } catch (ClassNotFoundException cannotHappen) {
        }

        return clone;
    }

    // NavigableMap API methods

    //获取第一个节点
    public Map.Entry<K,V> firstEntry() {
        return exportEntry(getFirstEntry());
    }

    //获取最后一个节点
    public Map.Entry<K,V> lastEntry() {
        return exportEntry(getLastEntry());
    }

    //获取第一个节点,并将改节点从TreeMap中删除。
    public Map.Entry<K,V> pollFirstEntry() {
        Entry<K,V> p = getFirstEntry();
        Map.Entry<K,V> result = exportEntry(p);
        if (p != null)//删除该节点
            deleteEntry(p);
        return result;
    }

    // 获取最后一个节点,并将改节点从TreeMap中删除。
    public Map.Entry<K,V> pollLastEntry() {
        Entry<K,V> p = getLastEntry();
        Map.Entry<K,V> result = exportEntry(p);
        if (p != null)
            deleteEntry(p);
        return result;
    }

    //返回 < key的最大节点的键值对 不存在返回null
    public Map.Entry<K,V> lowerEntry(K key) {
        return exportEntry(getLowerEntry(key));
    }

    //返回 < key的最大节点的key值
    public K lowerKey(K key) {
        return keyOrNull(getLowerEntry(key));
    }

    //返回 <= key的最大节点的键值对
    public Map.Entry<K,V> floorEntry(K key) {
        return exportEntry(getFloorEntry(key));
    }

    //返回 <= key的最节点的key
    public K floorKey(K key) {
        return keyOrNull(getFloorEntry(key));
    }

    //返回 >= key的最小节点键值对
    public Map.Entry<K,V> ceilingEntry(K key) {
        return exportEntry(getCeilingEntry(key));
    }

    //返回 >= key的最小节点的key
    public K ceilingKey(K key) {
        return keyOrNull(getCeilingEntry(key));
    }

    //返回 > key的最小节点的键值对
    public Map.Entry<K,V> higherEntry(K key) {
        return exportEntry(getHigherEntry(key));
    }

    //返回 > key的最小节点的key
    public K higherKey(K key) {
        return keyOrNull(getHigherEntry(key));
    }

    private transient EntrySet entrySet;//treemap的键值对集合
    private transient KeySet<K> navigableKeySet;
    private transient NavigableMap<K,V> descendingMap;//键值对的倒叙映射

    //返回所有键的集合
    public Set<K> keySet() {
        return navigableKeySet();
    }

    
    public NavigableSet<K> navigableKeySet() {
        KeySet<K> nks = navigableKeySet;
        return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
    }

   
    public NavigableSet<K> descendingKeySet() {
        return descendingMap().navigableKeySet();
    }

    //返回所有值的集合
    public Collection<V> values() {
        Collection<V> vs = values;
        return (vs != null) ? vs : (values = new Values());
    }

    //返回键值对集合
    public Set<Map.Entry<K,V>> entrySet() {
        EntrySet es = entrySet;
        return (es != null) ? es : (entrySet = new EntrySet());
    }

    //返回集合的降序后的集合 实际返回了集合的倒叙
    public NavigableMap<K, V> descendingMap() {
        NavigableMap<K, V> km = descendingMap;
        return (km != null) ? km : (descendingMap = new DescendingSubMap<>(this,
                                                    true, null, true,
                                                    true, null, true));
    }

    //返回一个从fromKey到tokey的集合(该范围的值包含于treemap集合)   fromInclusive toInclusive表示是否包含该节点
    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表示是否包含该节点
    public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
        return new AscendingSubMap<>(this,
                                     true,  null,  true,
                                     false, toKey, inclusive);
    }

    //返回范围从fromKey到尾节点的集合 inclusive表示是否包含该节点
    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);
    }

    @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;
    }
	//根据key替换value值
    @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();
            }
        }
    }

	// TreeMap的值的集合 对应的类
    class Values extends AbstractCollection<V> {
        public Iterator<V> iterator() {
            return new ValueIterator(getFirstEntry());
        }
		//所有值的长度
        public int size() {
            return TreeMap.this.size();
        }
		//是否包含某个值
        public boolean contains(Object o) {
            return TreeMap.this.containsValue(o);
        }
		//删除集合对象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() {
            TreeMap.this.clear();
        }

        public Spliterator<V> spliterator() {
            return new ValueSpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
        }
    }
	
	//键值对集合对应的类
    class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator(getFirstEntry());
        }

        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 TreeMap.this.size();
        }

        public void clear() {
            TreeMap.this.clear();
        }

        public Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
        }
    }

    //返回集合key值迭代器(顺序)
    Iterator<K> keyIterator() {
        return new KeyIterator(getFirstEntry());
    }
	//倒叙返回key值迭代器
    Iterator<K> descendingKeyIterator() {
        return new DescendingKeyIterator(getLastEntry());
    }
	//key的集合
    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
        private final NavigableMap<E, ?> m;
        KeySet(NavigableMap<E,?> map) { m = map; }

        public Iterator<E> iterator() {
            if (m instanceof TreeMap)
                return ((TreeMap<E,?>)m).keyIterator();
            else
                return ((TreeMap.NavigableSubMap<E,?>)m).keyIterator();
        }

        public Iterator<E> descendingIterator() {
            if (m instanceof TreeMap)
                return ((TreeMap<E,?>)m).descendingKeyIterator();
            else
                return ((TreeMap.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;
        }
        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() {
            return keySpliteratorFor(m);
        }
    }


    //根据比较器比较2个对象大小
    @SuppressWarnings("unchecked")
    final int compare(Object k1, Object k2) {
        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : comparator.compare((K)k1, (K)k2);
    }

    //当o1 o2不为空 比较2个值是否相等
    static final boolean valEquals(Object o1, Object o2) {
        return (o1==null ? o2==null : o1.equals(o2));
    }

    //返回键值对的拷贝对象
    static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
        return (e == null) ? null : new AbstractMap.SimpleImmutableEntry<>(e);
    }

    //当key不为空 返回key值
    static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
        return (e == null) ? null : e.key;
    }

    //返回key值 如果key==null 抛出异常
    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> {
        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;

        /**
         * Make a new cell with given key, value, and parent, and with
         * {@code null} child links, and BLACK color.
         */
        Entry(K key, V value, Entry<K,V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

        /**
         * Returns the key.
         *
         * @return the key
         */
        public K getKey() {
            return key;
        }

        /**
         * Returns the value associated with the key.
         *
         * @return the value associated with the key
         */
        public V getValue() {
            return value;
        }

        /**
         * Replaces the value currently associated with the key with the given
         * value.
         *
         * @return the value associated with the key before this method was
         *         called
         */
        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;
        }
    }

    //获取第一个节点
    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;
    }

    //返回指定项的继承项,如果没有继承项,则返回null。
    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> 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> p = t.parent;
            Entry<K,V> ch = t;
            while (p != null && ch == p.right) {
                ch = p;
                p = p.parent;
            }
            return p;
        }
    }

    //返回指定项的前身,如果没有,则返回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);
    }
	//返回当前节点的父节点
    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;//新插入节点为红色

		/**
		 * parentOf(x) : 当x不为空  获取其父节点
		 * leftOf(x) : x不为空 获取其左子节点
		 * rightOf(x) : x不为空 获取其右子节点
		 * colorOf(x) : x == null ? BLACK : x.color
		 */
        while (x != null && x != root && x.parent.color == RED) {//节点不为空且不是根节点  且颜色为红色
            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {//父节点是祖先节点的左子节点时  
                Entry<K,V> y = rightOf(parentOf(parentOf(x)));//令y节点为祖先节点的右子节点
                if (colorOf(y) == RED) {//y节点为红色时
                    setColor(parentOf(x), BLACK);//当x的父节点不为空时 令其颜色为黑色
                    setColor(y, BLACK);//y节点不为空时  令y节点颜色为黑色
                    setColor(parentOf(parentOf(x)), RED);//x的祖先节点不为空 使其颜色为红色
                    x = parentOf(parentOf(x));//令x的祖先节点赋值给x
                } else {//否则y节点颜色为黑色时
                    if (x == rightOf(parentOf(x))) {//x父节点的右子节点 等于x时
                        x = parentOf(x);//把x的父节点赋值给x
                        rotateLeft(x);//x节点进行左旋转
                    }
                    setColor(parentOf(x), BLACK);//把x的父节点设置为黑色
                    setColor(parentOf(parentOf(x)), RED);//把x的祖先节点设置为红色
                    rotateRight(parentOf(parentOf(x)));//x的祖先节点右旋转
                }
            } else {
                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));
                } else {
                    if (x == leftOf(parentOf(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) {
        modCount++;
        size--;

        // If strictly internal, copy successor's element to p and then make p
        // point to successor.
        if (p.left != null && p.right != null) {
            Entry<K,V> s = successor(p);
            p.key = s.key;
            p.value = s.value;
            p = s;
        } // p has 2 children

        // Start fixup at replacement node, if it exists.
        Entry<K,V> replacement = (p.left != null ? p.left : p.right);

        if (replacement != null) {
            // Link replacement to parent
            replacement.parent = p.parent;
            if (p.parent == null)
                root = replacement;
            else if (p == p.parent.left)
                p.parent.left  = replacement;
            else
                p.parent.right = replacement;

            // Null out links so they are OK to use by fixAfterDeletion.
            p.left = p.right = p.parent = null;

            // Fix replacement
            if (p.color == BLACK)
                fixAfterDeletion(replacement);
        } else if (p.parent == null) { // return if we are the only node.
            root = null;
        } else { //  No children. Use self as phantom replacement and unlink.
            if (p.color == BLACK)
                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;
            }
        }
    }

    //修改节点
    private void fixAfterDeletion(Entry<K,V> x) {
        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));
                    sib = rightOf(parentOf(x));
                }

                if (colorOf(leftOf(sib))  == BLACK &&
                    colorOf(rightOf(sib)) == BLACK) {
                    setColor(sib, RED);
                    x = parentOf(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 { // symmetric
                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);
    }

    private static final long serialVersionUID = 919286545866124006L;

    //把map集合实例保存到流里
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out the Comparator and any hidden stuff
        s.defaultWriteObject();

        // Write out size (number of Mappings)
        s.writeInt(size);

        // Write out keys and values (alternating)
        for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
            Map.Entry<K,V> e = i.next();
            s.writeObject(e.getKey());
            s.writeObject(e.getValue());
        }
    }

    //从流里吧实例读取出来
    private void readObject(final java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in the Comparator and any hidden stuff
        s.defaultReadObject();

        // Read in size
        int size = s.readInt();

        buildFromSorted(size, null, s, null);
    }

    //仅从TreeSet.readObject中调用
    void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
        throws java.io.IOException, ClassNotFoundException {
        buildFromSorted(size, null, s, defaultVal);
    }

    //只打算从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) {
        }
    }


    //基于排序数据的线性时间树构建算法。
    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);
    }

   
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值