`

读TreeMap源码

阅读更多
//一个基于二叉红黑树实现的map
//关于红黑树http://blog.csdn.net/chenssy/article/details/26668941这篇博客写的非常好
//另外TreeSet的是用TreeMap实现的。(组合设计模式,将所有的实现委托给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 V put(K key, V value) {
        Entry<K,V> t = root;
	//如果root是null,则直接放入root。
        if (t == null) {
	    //检查是否实现了Comparable接口,以及释放传入的是null
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }

        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;
	//如果传入了comparator
        if (cpr != null) {
            do {
	    //无限循环设置位置
                parent = 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);
        }
	//如果Comparable是null
        else {
            if (key == null)
                throw new NullPointerException();
            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);
        }
        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;
    }

 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)))) {
                Entry<K,V> y = rightOf(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 == rightOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateLeft(x);
                    }
                    setColor(parentOf(x), BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    rotateRight(parentOf(parentOf(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;
    }

   final int compare(Object k1, Object k2) {
        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : comparator.compare((K)k1, (K)k2);
    }


//新增map
public void putAll(Map<? extends K, ? extends V> map) {
        int mapSize = map.size();
	//如果当前集合是空的并且map是SortedMap
        if (size==0 && mapSize!=0 && map instanceof SortedMap) {
            Comparator c = ((SortedMap)map).comparator();
	    //如果用的比较器相同
            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;
            }
        }
	//如果不是put方法
        super.putAll(map);
    }

  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);
    }

//根据key获取值
 public V get(Object key) {
        Entry<K,V> p = getEntry(key);
        return (p==null ? null : p.value);
    }


final Entry<K,V> getEntry(Object key) {
        // Offload comparator-based version for sake of performance
        if (comparator != null)
	   //当有比较器
            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;
    }

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;
    }

//根据key删除值
 public V remove(Object key) {
        Entry<K,V> p = getEntry(key);
        if (p == null)
            return null;

        V oldValue = p.value;
        deleteEntry(p);
        return oldValue;
    }


 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;
            }
        }
    }

//返回map的长度
  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))
            if (valEquals(value, e.value))
                return true;
        return false;
    }

//获取最左边的作为也就是第一个entry
 final Entry<K,V> getFirstEntry() {
        Entry<K,V> p = root;
        if (p != null)
            while (p.left != null)
                p = p.left;
        return p;
    }

//找寻下一个节点
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;
        }
    }


static final boolean valEquals(Object o1, Object o2) {
        return (o1==null ? o2==null : o1.equals(o2));
    }

//返回映射中第一个key,即树最左边的key
 public K firstKey() {
        return key(getFirstEntry());
    }

 static <K> K key(Entry<K,?> e) {
        if (e==null)
            throw new NoSuchElementException();
        return e.key;
    }


//获取最后一个 即最右边的entry
 final Entry<K,V> getLastEntry() {
        Entry<K,V> p = root;
        if (p != null)
            while (p.right != null)
                p = p.right;
        return p;
    }

//获取最大的键即最右边的键
 public K lastKey() {
        return key(getLastEntry());
    }

//清空集合
public void clear() {
        modCount++;
        size = 0;
        root = null;
    }

//获取最左边的entry(最低位的entry)
 public Map.Entry<K,V> firstEntry() {
        return exportEntry(getFirstEntry());
    }

//转成SimpleImmutableEntry。
static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
        return (e == null) ? null :
            new AbstractMap.SimpleImmutableEntry<>(e);
    }

//获取最右边的entry(最高位的entry)
 public Map.Entry<K,V> lastEntry() {
        return exportEntry(getLastEntry());
    }


//移除最左边的键
 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;
    }

//移除最右边的键
 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;
    }

//返回小于当前键的最大entry
public Map.Entry<K,V> lowerEntry(K key) {
        return exportEntry(getLowerEntry(key));
    }

//返回小于当前键的最大entry
   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 K lowerKey(K key) {
        return keyOrNull(getLowerEntry(key));
    }

 static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
        return (e == null) ? null : e.key;
    }


//返回小于等于键的最大entry
public Map.Entry<K,V> floorEntry(K key) {
        return exportEntry(getFloorEntry(key));
    }

//返回小于等于键的最大键
public K floorKey(K key) {
        return keyOrNull(getFloorEntry(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;
    }


//返回大于等于给定键的最小entry
 public Map.Entry<K,V> ceilingEntry(K key) {
        return exportEntry(getCeilingEntry(key));
    }

//返回大于等于给定键的最小key
public K ceilingKey(K key) {
        return keyOrNull(getCeilingEntry(key));
    }

final Entry<K,V> getCeilingEntry(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 (cmp > 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;
                }
            } else
                return p;
        }
        return null;
    }

//返回大于key的最小entry
 public Map.Entry<K,V> higherEntry(K key) {
        return exportEntry(getHigherEntry(key));
    }

//返回大于key的最小key
 public K higherKey(K key) {
        return keyOrNull(getHigherEntry(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;
    }


//返回key的set集合
 public Set<K> keySet() {
        return navigableKeySet();
    }

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


  static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
        private final NavigableMap<E, Object> m;
        KeySet(NavigableMap<E,Object> map) { m = map; }

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

        public Iterator<E> descendingIterator() {
            if (m instanceof TreeMap)
                return ((TreeMap<E,Object>)m).descendingKeyIterator();
            else
                return (Iterator<E>)(((TreeMap.NavigableSubMap)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,Object> e = m.pollFirstEntry();
            return (e == null) ? null : e.getKey();
        }
        public E pollLast() {
            Map.Entry<E,Object> 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());
        }
    }

//返回map的逆序视图
 public NavigableMap<K, V> descendingMap() {
        NavigableMap<K, V> km = descendingMap;
        return (km != null) ? km :
            (descendingMap = new DescendingSubMap(this,
                                                  true, null, true,
                                                  true, null, true));
    }

分享到:
评论

相关推荐

    Jdk1.8源码,包含sun的源码

    再比如,集合框架的`HashMap`和`TreeMap`等也进行了优化,提高了性能和线程安全性。 总而言之,JDK 1.8源码是一份宝贵的资源,它揭示了Java平台的内部运作细节,对于提升开发者的技术水平和解决问题的能力有着不可...

    JDK1.8源码完整版

    Lambda表达式是JDK1.8的一个重要特性,它简化了对匿名内部类的使用,使得代码更加简洁和易读。通过使用 Lambda,我们可以将函数作为参数传递,或者将函数直接定义为方法体。这在处理集合操作时尤其有用,配合Stream ...

    Map-main-源码.rar

    HashMap是非线程安全的,适合于高并发环境下的读操作。 二、TreeMap TreeMap使用红黑树作为底层数据结构,提供了有序的键值对存储。红黑树是一种自平衡的二叉查找树,它保证了插入、删除和查找的时间复杂度都是O...

    JAVA面向对象编程(孙卫琴)读书笔记(三)

    - 集合框架是Java中用于存储和操作对象的工具,包括List(如ArrayList和LinkedList)、Set(如HashSet和TreeSet)和Map(如HashMap和TreeMap)。 - 泛型的引入增强了集合框架的类型安全,防止了运行时类型转换异常...

    Java_jihe2.rar_java集合

    - `CopyOnWriteArrayList`和`CopyOnWriteArraySet`:适用于读多写少的场景,线程安全。 7. **集合操作** - `add()`、`remove()`:添加和移除元素。 - `contains()`、`equals()`:检查元素是否存在或集合是否相等...

    Java基础学习25.pdf

    - ConcurrentSkipListMap:线程安全的TreeMap实现,适用于大量读操作的场景。 - ConcurrentSkipListSet:线程安全的TreeSet实现,基于ConcurrentSkipListMap。 - CopyOnWriteArraySet:基于CopyOnWriteArrayList...

    浅谈JAVA集合框架及其应用.pdf

    本文将从源码分析角度出发,深入探讨Java集合框架中常用的接口和实现类的底层数据结构及其特点,并探讨其在实际业务开发中的应用选择。 Java集合框架中的数据结构主要分为两大类:Collection集合和Map集合。...

    大厂必学BAT面试题汇总及详解

    事务的隔离级别有读未提交、读已提交、可重复读、串行化。MySQL的binlog有ROW、STATEMENT、MIXED三种模式,各有优缺点。分布式事务解决方案如2PC、3PC。数据库事务隔离级别决定了并发操作的可见性和一致性,MySQL...

    20-BAT面试题汇总及详解(进大厂必看).docx

    红黑树是一种自平衡的二叉查找树,常用于集合框架如`TreeMap`和`TreeSet`。NIO(Non-blocking I/O)适用于大量连接、低延迟的场景,它允许程序在等待I/O操作完成时执行其他任务。Java9引入了模块系统、JShell(REPL...

    整理了一个关于网上java问与答的一个手册

    3. HashMap与TreeMap:HashMap提供快速查找,TreeMap保持元素排序。 四、泛型 1. 泛型引入的目的:类型安全,编译时检查类型,避免强制类型转换。 2. 类、接口、方法均可使用泛型,如ArrayList,函数式接口Function...

    Java JDK实例宝典

    LinkedHashMap和TreeMap 4. 12 对Map排序 4. 13 Properties属性文件 第5章 字符串 5. 1 使用String 5. 2 基本数据类型与字符串的转化 5. 3 判断Java标识符 5. 4 使用StringBuffer ...

    JavaTraining2

    4. **集合框架**:Java集合框架是处理对象集合的重要工具,包括List(如ArrayList和LinkedList)、Set(如HashSet和TreeSet)和Map(如HashMap和TreeMap)接口及其实现类,以及泛型的使用。 5. **异常处理**:学习...

    Programming_Challenge_Query

    4. **集合框架**:Java集合框架包括List(如ArrayList, LinkedList)、Set(如HashSet, TreeSet)和Map(如HashMap, TreeMap)。挑战可能要求你使用这些数据结构存储和操作数据。 5. **IO流**:如果你需要读取或...

Global site tag (gtag.js) - Google Analytics