Java TreeMap源码总结 TreeMap源码注释翻译和解析中英文对照版

版本
JDK8(JDK1.8)

TreeMap源码重点
1.TreeMap是有序的,映射根据其键的实现的Comparable接口自然排序(从小到大),或者由映射创建时提供的Comparator接口实现类进行排序,具体取决于使用的构造函数。

2.TreeMap操作是非同步的,所以多线程使用时必须在其外部使用synchronized同步锁或者使用SortedMap m = Collections.synchronizedSortedMap(new TreeMap(…)) 来包装TreeMap使其变成同步集合

3.自然排序默认键不能为null

4.红黑树实现为 containsKey()、get()、put()和remove() 操作提供了保证的log(n)时间开销

5.TreeMap底层由红黑树实现,红黑树基于NavigableMap接口类实现

TreeMap部分源码

package java.util;

import java.io.Serializable;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;

/**
 * A Red-Black tree based {@link NavigableMap} implementation.
 * The map is sorted according to the {@linkplain Comparable natural
 * ordering} of its keys, or by a {@link Comparator} provided at map
 * creation time, depending on which constructor is used.
 * 红黑树基于NavigableMap类实现。
 * 映射根据其键的实现的Comparable接口自然排序,
 * 或者由映射创建时提供的Comparator接口实现类进行排序,具体取决于使用的构造函数。
 * 
 *
 * <p>This implementation provides guaranteed log(n) time cost for the
 * {@code containsKey}, {@code get}, {@code put} and {@code remove}
 * operations.  Algorithms are adaptations of those in Cormen, Leiserson, and
 * Rivest's <em>Introduction to Algorithms</em>.
 * 此实现为 containsKey()、get()、put()和remove()
 * 操作提供了保证的log(n)时间开销。
 * 算法是对Cormen、Leiserson和Rivest的算法介绍中的算法的改编。
 * 
 * 
 * 
 *
 * <p>Note that the ordering maintained by a tree map, like any sorted map, and
 * whether or not an explicit comparator is provided, must be <em>consistent
 * with {@code equals}</em> if this sorted map is to correctly implement the
 * {@code Map} interface.  (See {@code Comparable} or {@code Comparator} for a
 * precise definition of <em>consistent with equals</em>.)  This is so because
 * the {@code Map} interface is defined in terms of the {@code equals}
 * operation, but a sorted map performs all key comparisons using its {@code
 * compareTo} (or {@code compare}) method, so two keys that are deemed equal by
 * this method are, from the standpoint of the sorted map, equal.  The behavior
 * of a sorted map <em>is</em> well-defined even if its ordering is
 * inconsistent with {@code equals}; it just fails to obey the general contract
 * of the {@code Map} interface.
 * 请注意,与任何排序映射一样,
 * 树映射维护的顺序以及是否提供了显式比较器都必须与equals()一致,
 * 如果此排序映射要正确实现map接口(请参阅Comparable接口
 * 或Comparator接口以获得与equals一致的精确定义。)
 * 这是因为Map接口是根据equals()操作定义的,
 * 但排序映射使用其compareTo(或compare)方法执行所有键比较,
 * 因此,从排序映射的角度来看,用这种方法认为相等的两个键是相等的。
 * 即使排序映射的顺序与equals不一致,它的行为也是定义良好的;
 * 它只是没有遵守Map接口的规定。
 * 
 * 
 * 
 * 
 * <p><strong>Note that this implementation is not synchronized.</strong>
 * If multiple threads access a map concurrently, and at least one of the
 * threads modifies the map structurally, it <em>must</em> be synchronized
 * externally.  (A structural modification is any operation that adds or
 * deletes one or more mappings; merely changing the value associated
 * with an existing key is not a structural modification.)  This is
 * typically accomplished by synchronizing on some object that naturally
 * encapsulates the map.
 * 请注意,此实现是不同步的。如果多个线程同时访问一个映射,
 * 并且至少有一个线程在结构上修改了映射,
 * 那么它必须在外部同步(结构修改是添加或删除一个或多个映射的任何操作;
 * 仅更改与现有键关联的值不是结构性修改。)这通常通过在自然封装映射的某个对象上进行同步来实现。
 * 
 * 
 * 
 * If no such object exists, the map should be "wrapped" using the
 * {@link Collections#synchronizedSortedMap Collections.synchronizedSortedMap}
 * method.  This is best done at creation time, to prevent accidental
 * unsynchronized access to the map: <pre>
 *   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));</pre>
 * 如果不存在这样的对象,则应使用Collections类的synchronizedSortedMap方法
 * “包装”映射。这最好在创建时完成,以防止对映射的意外非同步访问:
 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
 * 即TreeMap不是同步的,要么在外部使用synchronzied来使其同步,或者使用
 * Collection类的synchronizedSortedMap方法 将一个新创建的TreeMap对象变成同步的容器
 * 
 * 
 * 
 * 
 * <p>The iterators returned by the {@code iterator} method of the collections
 * returned by all of this class's "collection view methods" are
 * <em>fail-fast</em>: if the map is structurally modified at any time after
 * the iterator is created, in any way except through the iterator's own
 * {@code remove} method, the iterator will throw a {@link
 * ConcurrentModificationException}.  Thus, in the face of concurrent
 * modification, the iterator fails quickly and cleanly, rather than risking
 * arbitrary, non-deterministic behavior at an undetermined time in the future.
 * 该类的所有“集合视图方法”返回的集合的iterator()方法返回的迭代器都是快速失败的:
 * 如果在创建迭代器后的任何时间,以任何方式修改映射的结构,
 * 除了通过迭代器自己的remove()方法之外,
 * 迭代器将抛出ConcurrentModificationException异常。
 * 因此,在面对并发修改时,迭代器会快速、利索地失败,
 * 而不是在将来的不确定时间冒着任意、不确定行为的风险。
 * 
 * 
 * 
 *
 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
 * as it is, generally speaking, impossible to make any hard guarantees in the
 * presence of unsynchronized concurrent modification.  Fail-fast iterators
 * throw {@code ConcurrentModificationException} on a best-effort basis.
 * Therefore, it would be wrong to write a program that depended on this
 * exception for its correctness:   <em>the fail-fast behavior of iterators
 * should be used only to detect bugs.</em>
 * 请注意,无法保证迭代器的快速失效行为,因为一般来说,
 * 在存在非同步并发修改的情况下,不可能做出任何硬保证。
 * 快速失效迭代器尽最大努力抛出ConcurrentModificationException异常。
 * 因此,编写依赖于此异常的正确性的程序是错误的:迭代器的快速失败行为应该只用于检测bug。
 * 
 * 
 * 
 *
 * <p>All {@code Map.Entry} pairs returned by methods in this class
 * and its views represent snapshots of mappings at the time they were
 * produced. They do <strong>not</strong> support the {@code Entry.setValue}
 * method. (Note however that it is possible to change mappings in the
 * associated map using {@code put}.)
 * 此类中的方法及其视图返回的所有 Map.Entry对表示生成映射时映射的快照。
 * 它们不支持Entry.setValue()方法(但是请注意,可以使用put()更改关联映射中的映射。)
 * 
 * 
 * 
 *
 * <p>This class is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @param <K> the type of keys maintained by this map 此映射维护的键的类型
 * @param <V> the type of mapped values 此映射维护的值的类型
 *
 * @author  Josh Bloch and Doug Lea
 * @see Map
 * @see HashMap
 * @see Hashtable
 * @see Comparable
 * @see Comparator
 * @see Collection
 * @since 1.2
 */

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
    /**
     * The comparator used to maintain order in this tree map, or
     * null if it uses the natural ordering of its keys.
     * 用于维护此树映射中的顺序的比较器,如果它使用其键的自然顺序,则为null。
     * @serial
     */
    private final Comparator<? super K> comparator;

    private transient Entry<K,V> root;

    /**
     * The number of entries in the tree 树容器的初始容量
     */
    private transient int size = 0;

    /**
     * The number of structural modifications to the tree.
     * 对树进行结构修改的次数。
     */
    private transient int modCount = 0;

    /**
     * Constructs a new, empty tree map, using the natural ordering of its
     * keys.  All keys inserted into the map must implement the {@link
     * Comparable} interface.  Furthermore, all such keys must be
     * <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
     * a {@code ClassCastException} for any keys {@code k1} and
     * {@code k2} in the map.  If the user attempts to put a key into the
     * map that violates this constraint (for example, the user attempts to
     * put a string key into a map whose keys are integers), the
     * {@code put(Object key, Object value)} call will throw a
     * {@code ClassCastException}.
     * 使用键的自然顺序构造新的空树映射。
     * 插入到映射中的所有键都必须实现Comparable接口。
     * 此外,所有这些键必须是相互可比的:k1.compareTo(k2)
     * 不能为映射中的任何键k1和k2抛出 ClassCastException异常。
     * 如果用户试图将违反此约束的键放入映射(例如,用户试图将字符串键放入键为整数的映射),
     * 则put(Object key,Object value) 调用将抛出ClassCastException异常。
     * 
     * ClassCastException是JVM在检测到两个类型间转换不兼容时引发的运行时异常。
     */
    public TreeMap() {
        comparator = null;
    }

    /**
     * Constructs a new, empty tree map, ordered according to the given
     * comparator.  All keys inserted into the map must be <em>mutually
     * comparable</em> by the given comparator: {@code comparator.compare(k1,
     * k2)} must not throw a {@code ClassCastException} for any keys
     * {@code k1} and {@code k2} in the map.  If the user attempts to put
     * a key into the map that violates this constraint, the {@code put(Object
     * key, Object value)} call will throw a
     * {@code ClassCastException}.
     * 构造一个新的空树映射,根据给定的比较器进行排序。
     * 插入到映射中的所有键必须由给定的比较器相互比较:
     * comparator.compare(k1,k2) 有给定比较器的compare方法比较
     * 不能为映射中的任何键k1和k2抛出 ClassCastException异常。
     * 如果用户试图将违反此约束的键放入映射(例如,用户试图将字符串键放入键为整数的映射),
     * 则put(Object key,Object value) 调用将抛出ClassCastException异常。
     * 
     * 
     *
     * @param comparator the comparator that will be used to order this map.
     *        If {@code null}, the {@linkplain Comparable natural
     *        ordering} of the keys will be used.
     * 用于排序此映射的比较器。如果传入null,将使用键的自然顺序比较。
     */
    public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

    /**
     * Constructs a new tree map containing the same mappings as the given
     * map, ordered according to the <em>natural ordering</em> of its keys.
     * All keys inserted into the new map must implement the {@link
     * Comparable} interface.  Furthermore, all such keys must be
     * <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
     * a {@code ClassCastException} for any keys {@code k1} and
     * {@code k2} in the map.  This method runs in n*log(n) time.
     * 构造一个新的树映射,其中包含与给定映射相同的映射,
     * 并根据其键的自然顺序进行排序。
     * 插入到新映射中的所有键都必须实现Comparable接口。
     * 此外,所有这些键必须是相互可比的k1.compareTo(k2)
     * 不能为映射中的任何键k1和k2抛出ClassCastException异常。
     * 此方法在n*log(n)时间内运行。
     * 
     * 
     *
     * @param  m the map whose mappings are to be placed in this map
     * @throws ClassCastException if the keys in m are not {@link Comparable},
     *         or are not mutually comparable
     * @throws NullPointerException if the specified map is null
     */
    public TreeMap(Map<? extends K, ? extends V> m) {
        comparator = null;
        putAll(m);
    }

    /**
     * Constructs a new tree map containing the same mappings and
     * using the same ordering as the specified sorted map.  This
     * method runs in linear time.
     * 构造一个新的树映射,该树映射包含与指定的排序映射相同的映射并使用相同的顺序。
     * 此方法以线性时间运行。
     *
     * @param  m the sorted map whose mappings are to be placed in this map,
     *         and whose comparator is to be used to sort this map
     * @throws NullPointerException if the specified map is null
     */
    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 查询操作

    /**
     * Returns the number of key-value mappings in this map.
     * 返回此映射中的键值映射数。
     * @return the number of key-value mappings in this map
     */
    public int size() {
        return size;
    }

    /**
     * Returns {@code true} if this map contains a mapping for the specified
     * key.
     * 如果此映射包含指定键的映射,则返回true。
     *
     * @param key key whose presence in this map is to be tested
     * @return {@code true} if this map contains a mapping for the
     *         specified key
     * @throws ClassCastException if the specified key cannot be compared
     *         with the keys currently in the map
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     */
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }

    /**
     * Returns {@code true} if this map maps one or more keys to the
     * specified value.  More formally, returns {@code true} if and only if
     * this map contains at least one mapping to a value {@code v} such
     * that {@code (value==null ? v==null : value.equals(v))}.  This
     * operation will probably require time linear in the map size for
     * most implementations.
     * 如果此映射将一个或多个键映射到指定值,则返回true。
     * 更正式地说,返回true时候当且仅当此映射包含至少一个到值v的映射,
     * 使得(value==null?v==null:value.equals(v))。
     * 对于大多数实现,此操作可能需要映射大小的线性时间n。
     *
     * @param value value whose presence in this map is to be tested
     * @return {@code true} if a mapping to {@code value} exists;
     *         {@code false} otherwise
     * @since 1.2
     */
    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;
    }

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     * 返回指定键映射到的值,如果此映射不包含该键的映射,则返回null。
     * 
     * 
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code key} compares
     * equal to {@code k} according to the map's ordering, then this
     * method returns {@code v}; otherwise it returns {@code null}.
     * (There can be at most one such mapping.)
     * 更正式地说,如果此映射包含从键k到值v的映射,
     * 使得key根据映射的顺序比较等于k,则此方法返回v;
     * 否则返回null(最多可以有一个这样的映射。)
     * 
     * 
     *
     * <p>A return value of {@code null} does not <em>necessarily</em>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     * 返回值null不一定表示映射不包含键的映射;
     * 映射也可能显式地将键映射到null。
     * 使用containsKey()操作可用于区分这两种情况。
     * 
     *
     * @throws ClassCastException if the specified key cannot be compared
     *         with the keys currently in the map
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     */
    public V get(Object key) {
        Entry<K,V> p = getEntry(key);
        return (p==null ? null : p.value);
    }

    public Comparator<? super K> comparator() {
        return comparator;
    }

    /**
     * @throws NoSuchElementException {@inheritDoc}
     */
    public K firstKey() {
        return key(getFirstEntry());
    }

    /**
     * @throws NoSuchElementException {@inheritDoc}
     */
    public K lastKey() {
        return key(getLastEntry());
    }

    /**
     * Copies all of the mappings from the specified map to this map.
     * These mappings replace any mappings that this map had for any
     * of the keys currently in the specified map.
     * 将指定映射中的所有映射复制到此映射。
     * 这些映射将替换此映射对指定映射中当前任何键所具有的任何映射。
     * 即传入的map和此map如果有相同的键,则会覆盖当前键位对应的值
     * @param  map mappings to be stored in this map
     * @throws ClassCastException if the class of a key or value in
     *         the specified map prevents it from being stored in this map
     * @throws NullPointerException if the specified map is null or
     *         the specified map contains a null key and this map does not
     *         permit null keys
     */
    public void putAll(Map<? extends K, ? extends V> map) {
        int mapSize = map.size();
        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;
            }
        }
        super.putAll(map);
    }

    /**
     * Returns this map's entry for the given key, or {@code null} if the map
     * does not contain an entry for the key.
     * 返回给定键的此映射项,如果映射不包含该键的项,则返回null。
     *
     * @return this map's entry for the given key, or {@code null} if the map
     *         does not contain an entry for the key
     * @throws ClassCastException if the specified key cannot be compared
     *         with the keys currently in the map
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     */
    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();
        @SuppressWarnings("unchecked")
            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;
    }

    /**
     * Version of getEntry using comparator. Split off from getEntry
     * for performance. (This is not worth doing for most methods,
     * that are less dependent on comparator performance, but is
     * worthwhile here.)
     * 使用comparator的getEntry版本。
     * 从getEntry分离以获得性能(对于大多数不太依赖于比较器性能的方法来说,
     * 这是不值得的,但在这里是值得的。)
     * 
     */
    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)
                    p = p.left;
                else if (cmp > 0)
                    p = p.right;
                else
                    return p;
            }
        }
        return null;
    }

    /**
     * Gets the entry corresponding to the specified key; if no such entry
     * exists, returns the entry for the least key greater than the specified
     * key; if no such entry exists (i.e., the greatest key in the Tree is less
     * than the specified key), returns {@code null}.
     * 获取与指定键对应的项;如果不存在此类条目,
     * 则返回大于指定键的最小键的条目;
     * 如果不存在这样的条目(即树中最大的键小于指定的键),则返回null。
     * 与最大键相等不返回
     * getHigherEntry(K 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;
    }

    /**
     * Gets the entry corresponding to the specified key; if no such entry
     * exists, returns the entry for the greatest key less than the specified
     * key; if no such entry exists, returns {@code null}.
     * 获取与指定键对应的项;如果不存在这样的条目,
     * 则返回小于指定密钥的最大密钥的条目;如果不存在这样的条目,则返回null。
     * 与最大键相等不返回
     * getLowerEntry(K 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;
    }

    /**
     * Gets the entry for the least key greater than the specified
     * key; if no such entry exists, returns the entry for the least
     * key greater than the specified key; if no such entry exists
     * returns {@code null}.
     * 获取大于指定键的最小键的项;如果不存在此类条目,
     * 则返回大于指定键的最小键的条目;如果不存在这样的条目,则返回null。
     * 与最大键相等也返回
     * getCeilingEntry(K 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;
    }

    

    /**
     * Returns the entry for the greatest key less than the specified key; if
     * no such entry exists (i.e., the least key in the Tree is greater than
     * the specified key), returns {@code null}.
     * 返回小于指定密钥的最大密钥的条目;
     * 如果不存在这样的条目(即树中最小的键大于指定的键),则返回null。
     * 与最大键相等也返回
     * getFloorEntry(K 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;
    }

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     * 将指定的值与此映射中的指定键相关联。如果映射以前包含键的映射,则旧的值被替换。
     *
     * @param key key with which the specified value is to be associated 与指定值关联的键
     * @param value value to be associated with the specified key 要与指定键关联的值
     *
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     *         与key关联的上一个值,如果key没有映射,则为null。
     *         (一个null返回值还可以指示之前将null与key关联的映射。)
     * 
     * 
     * @throws ClassCastException if the specified key cannot be compared
     *         with the keys currently in the map
     *         如果指定的key无法与map中当前key进行比较,即两种不是同类,
     *         或者同类但没有实现Comparable接口
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     *         如果指定的键为null,并且此映射使用自然排序,或者其比较器不允许null键,
     *         即自然排序也不允许键为空
     */
    public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            compare(key, key); // type (and possibly null) check 类型(可能为null)检查

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths 
        // 拆分comparator和comparable 比较路径
        // Comparator 使用 compare 比较
        // Comparable 使用 compareTo 比较
        Comparator<? super K> cpr = 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);
        }
        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);
        }
        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;
    }

    /**
     * Removes the mapping for this key from this TreeMap if present.
     * 从此树映射中删除此键的映射(如果存在)。
     *
     * @param  key key for which mapping should be removed 应删除其映射的键
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     *         与key关联的上一个值,如果key没有映射,则为null。
     *         (一个null返回值还可以指示之前将null与key关联的映射。)
     * @throws ClassCastException if the specified key cannot be compared
     *         with the keys currently in the map
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     */
    public V remove(Object key) {
        Entry<K,V> p = getEntry(key);
        if (p == null)
            return null;

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

    /**
     * Removes all of the mappings from this map. 从map中删除所有映射。
     * The map will be empty after this call returns. 此调用返回后,map将为空。
     */
    public void clear() {
        modCount++; // 对树进行结构修改的次数。
        size = 0;
        root = null;
    }

    /**
     * Returns a shallow copy of this {@code TreeMap} instance. (The keys and
     * values themselves are not cloned.)
     * 返回此TreeMap实例的浅层副本。(不会克隆键和值本身。)
     * 即浅拷贝,浅拷贝是类的基本类型会复制一份,
     * 而引用类型,只会复制引用,而不会复制引用类型,
     * 即在克隆后得到的map修改引用类型的值,
     * 原map会收到影响
     * @return a shallow copy of this map
     */
    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)
        // 将克隆置于“原始”状态(比较器除外)
        // 将一些map的属性设置为新的,当讲引用类型设为null是,
        // 则修改克隆得到的map的对应属性不会影响原map
        clone.root = null; // Entry<K,V> root
        clone.size = 0; // The number of entries in the tree 树容器的初始容量
        clone.modCount = 0;  // 对树进行结构修改的次数。
        clone.entrySet = null;
        clone.navigableKeySet = null;
        clone.descendingMap = null;

        // Initialize clone with our mappings
        // 使用我们的映射初始化克隆
        try {
            // entrySet() 返回值为 Set<Map.Entry<K,V>> 
            // entrySet().iterator() 为Iterator<Map.Entry<K,V>>
            clone.buildFromSorted(size, entrySet().iterator(), null, null);
        } catch (java.io.IOException cannotHappen) {
        } catch (ClassNotFoundException cannotHappen) {
        }

        return clone;
    }

    // NavigableMap API methods
    // NavigableMap API 方法
    // 导航 Map API 方法
    /**
     * @since 1.6
     */
    public Map.Entry<K,V> firstEntry() {
        return exportEntry(getFirstEntry());
    }

    /**
     * @since 1.6
     */
    public Map.Entry<K,V> lastEntry() {
        return exportEntry(getLastEntry());
    }

    /**
     * @since 1.6
     */
    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;
    }

    /**
     * @since 1.6
     */
    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;
    }

    /**
     * @throws ClassCastException {@inheritDoc}
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     * @since 1.6
     */
    public Map.Entry<K,V> lowerEntry(K key) {
        return exportEntry(getLowerEntry(key));
    }

    /**
     * @throws ClassCastException {@inheritDoc}
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     * @since 1.6
     */
    public K lowerKey(K key) {
        return keyOrNull(getLowerEntry(key));
    }

    /**
     * @throws ClassCastException {@inheritDoc}
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     * @since 1.6
     */
    public Map.Entry<K,V> floorEntry(K key) {
        return exportEntry(getFloorEntry(key));
    }

    /**
     * @throws ClassCastException {@inheritDoc}
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     * @since 1.6
     */
    public K floorKey(K key) {
        return keyOrNull(getFloorEntry(key));
    }

    /**
     * @throws ClassCastException {@inheritDoc}
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     * @since 1.6
     */
    public Map.Entry<K,V> ceilingEntry(K key) {
        return exportEntry(getCeilingEntry(key));
    }

    /**
     * @throws ClassCastException {@inheritDoc}
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     * @since 1.6
     */
    public K ceilingKey(K key) {
        return keyOrNull(getCeilingEntry(key));
    }

    /**
     * @throws ClassCastException {@inheritDoc}
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     * @since 1.6
     */
    public Map.Entry<K,V> higherEntry(K key) {
        return exportEntry(getHigherEntry(key));
    }

    /**
     * @throws ClassCastException {@inheritDoc}
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     * @since 1.6
     */
    public K higherKey(K key) {
        return keyOrNull(getHigherEntry(key));
    }

    // Views
    // 视图

    /**
     * Fields initialized to contain an instance of the entry set view
     * the first time this view is requested.  Views are stateless, so
     * there's no reason to create more than one.
     * 第一次请求该视图时,初始化为包含条目集视图实例的字段。
     * 视图是无状态的,因此没有理由创建多个视图。
     * 
     * 即当第一次调用entrySet()方法,才会初始化下面三个变量,
     * 且下面三个变量是没有实际数据的,它们只是map里面数据的
     * 视图,即修改map中的数据它们也会随之改变
     * 
     */
    private transient EntrySet entrySet;
    private transient KeySet<K> navigableKeySet;
    private transient NavigableMap<K,V> descendingMap;

    /**
     * Returns a {@link Set} view of the keys contained in this map.
     * 返回此映射中包含的键的Set视图。
     *
     * <p>The set's iterator returns the keys in ascending order.
     * 集合的迭代器按升序返回键。
     * 
     * The set's spliterator is
     * <em><a href="Spliterator.html#binding">late-binding</a></em>,
     * <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED}
     * and {@link Spliterator#ORDERED} with an encounter order that is ascending
     * key order.  The spliterator's comparator (see
     * {@link java.util.Spliterator#getComparator()}) is {@code null} if
     * the tree map's comparator (see {@link #comparator()}) is {@code null}.
     * Otherwise, the spliterator's comparator is the same as or imposes the
     * same total ordering as the tree map's comparator.
     * 集合的迭代器按升序返回键。集合的拆分器是延迟绑定、快速失效的,
     * 并且spliterator#SORTED和spliterator#ORDERED,其排序顺序为键升序。
     * 
     * 如果TreeMap类实现的comparator是null(使用comparator()查看),
     * 则spliterator类实现的comparator为null(使用java.util.Spliterator#getComparator()查看),
     * 否则,spliterator类实现的comparator与TreeMap类实现的comparator相同或施加相同的总排序。
     * 
     * spliterator 拆分器
     * 
     *
     * <p>The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own {@code remove} operation), the results of
     * the iteration are undefined.  The set supports element removal,
     * which removes the corresponding mapping from the map, via the
     * {@code Iterator.remove}, {@code Set.remove},
     * {@code removeAll}, {@code retainAll}, and {@code clear}
     * operations.  It does not support the {@code add} or {@code addAll}
     * operations.
     * 集合由映射支持,因此对映射的更改将反映在集合中,反之亦然。
     * 如果在对集合进行迭代时修改映射(通过迭代器自己的{@code remove}操作除外),
     * 则迭代的结果是未定义的。该集合支持元素移除,
     * 即通过Iterator.remove, Set.remove, TreeMap.removeAll, TreeMap.retainAll, TreeMap.clear
     * 操作从映射中移除相应的映射。它不支持TreeMap.add或TreeMap.addAll操作。
     * 
     * 即通过keySet得到的Set与TreeMap相互影响,
     * 在修改TreeMap时Set随之改变,
     * 且可以通过修改Set来改变TreeMap,但是仅限删除和清空之类的操作,
     * 对于添加操作则不支持
     * 
     */
    public Set<K> keySet() {
        return navigableKeySet();
    }

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

    /**
     * @since 1.6
     */
    public NavigableSet<K> descendingKeySet() {
        return descendingMap().navigableKeySet();
    }

    /**
     * Returns a {@link Collection} view of the values contained in this map.
     * 返回此映射中包含的值的Collection视图。
     *
     * <p>The collection's iterator returns the values in ascending order
     * of the corresponding keys. The collection's spliterator is
     * <em><a href="Spliterator.html#binding">late-binding</a></em>,
     * <em>fail-fast</em>, and additionally reports {@link Spliterator#ORDERED}
     * with an encounter order that is ascending order of the corresponding
     * keys.
     * 集合的迭代器按相应键的升序返回值。集合的拆分器是后期绑定的、快速失败的,
     * 并且spliterator#ORDERED,其排序顺序是相应键的升序
     * 
     *
     * <p>The collection is backed by the map, so changes to the map are
     * reflected in the collection, and vice-versa.  If the map is
     * modified while an iteration over the collection is in progress
     * (except through the iterator's own {@code remove} operation),
     * the results of the iteration are undefined.  The collection
     * supports element removal, which removes the corresponding
     * mapping from the map, via the {@code Iterator.remove},
     * {@code Collection.remove}, {@code removeAll},
     * {@code retainAll} and {@code clear} operations.  It does not
     * support the {@code add} or {@code addAll} operations.
     * 集合由映射支持,因此对映射的更改将反映在集合中,反之亦然。
     * 如果在对集合进行迭代时修改映射(通过迭代器自己的{@code remove}操作除外),
     * 则迭代的结果是未定义的。该集合支持元素移除,
     * 即通过Iterator.remove, Set.remove, TreeMap.removeAll, TreeMap.retainAll, TreeMap.clear
     * 操作从映射中移除相应的映射。它不支持TreeMap.add或TreeMap.addAll操作。
     * 
     */
    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lolxxs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值