TreeMap.java revision 0ad21d8aa7113a444ea23eeff002c3448c7d68f5
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27package java.util;
28
29import java.io.Serializable;
30import java.util.function.BiConsumer;
31import java.util.function.BiFunction;
32import java.util.function.Consumer;
33
34/**
35 * A Red-Black tree based {@link NavigableMap} implementation.
36 * The map is sorted according to the {@linkplain Comparable natural
37 * ordering} of its keys, or by a {@link Comparator} provided at map
38 * creation time, depending on which constructor is used.
39 *
40 * <p>This implementation provides guaranteed log(n) time cost for the
41 * {@code containsKey}, {@code get}, {@code put} and {@code remove}
42 * operations.  Algorithms are adaptations of those in Cormen, Leiserson, and
43 * Rivest's <em>Introduction to Algorithms</em>.
44 *
45 * <p>Note that the ordering maintained by a tree map, like any sorted map, and
46 * whether or not an explicit comparator is provided, must be <em>consistent
47 * with {@code equals}</em> if this sorted map is to correctly implement the
48 * {@code Map} interface.  (See {@code Comparable} or {@code Comparator} for a
49 * precise definition of <em>consistent with equals</em>.)  This is so because
50 * the {@code Map} interface is defined in terms of the {@code equals}
51 * operation, but a sorted map performs all key comparisons using its {@code
52 * compareTo} (or {@code compare}) method, so two keys that are deemed equal by
53 * this method are, from the standpoint of the sorted map, equal.  The behavior
54 * of a sorted map <em>is</em> well-defined even if its ordering is
55 * inconsistent with {@code equals}; it just fails to obey the general contract
56 * of the {@code Map} interface.
57 *
58 * <p><strong>Note that this implementation is not synchronized.</strong>
59 * If multiple threads access a map concurrently, and at least one of the
60 * threads modifies the map structurally, it <em>must</em> be synchronized
61 * externally.  (A structural modification is any operation that adds or
62 * deletes one or more mappings; merely changing the value associated
63 * with an existing key is not a structural modification.)  This is
64 * typically accomplished by synchronizing on some object that naturally
65 * encapsulates the map.
66 * If no such object exists, the map should be "wrapped" using the
67 * {@link Collections#synchronizedSortedMap Collections.synchronizedSortedMap}
68 * method.  This is best done at creation time, to prevent accidental
69 * unsynchronized access to the map: <pre>
70 *   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));</pre>
71 *
72 * <p>The iterators returned by the {@code iterator} method of the collections
73 * returned by all of this class's "collection view methods" are
74 * <em>fail-fast</em>: if the map is structurally modified at any time after
75 * the iterator is created, in any way except through the iterator's own
76 * {@code remove} method, the iterator will throw a {@link
77 * ConcurrentModificationException}.  Thus, in the face of concurrent
78 * modification, the iterator fails quickly and cleanly, rather than risking
79 * arbitrary, non-deterministic behavior at an undetermined time in the future.
80 *
81 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
82 * as it is, generally speaking, impossible to make any hard guarantees in the
83 * presence of unsynchronized concurrent modification.  Fail-fast iterators
84 * throw {@code ConcurrentModificationException} on a best-effort basis.
85 * Therefore, it would be wrong to write a program that depended on this
86 * exception for its correctness:   <em>the fail-fast behavior of iterators
87 * should be used only to detect bugs.</em>
88 *
89 * <p>All {@code Map.Entry} pairs returned by methods in this class
90 * and its views represent snapshots of mappings at the time they were
91 * produced. They do <strong>not</strong> support the {@code Entry.setValue}
92 * method. (Note however that it is possible to change mappings in the
93 * associated map using {@code put}.)
94 *
95 * <p>This class is a member of the
96 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
97 * Java Collections Framework</a>.
98 *
99 * @param <K> the type of keys maintained by this map
100 * @param <V> the type of mapped values
101 *
102 * @author  Josh Bloch and Doug Lea
103 * @see Map
104 * @see HashMap
105 * @see Hashtable
106 * @see Comparable
107 * @see Comparator
108 * @see Collection
109 * @since 1.2
110 */
111
112public class TreeMap<K,V>
113    extends AbstractMap<K,V>
114    implements NavigableMap<K,V>, Cloneable, java.io.Serializable
115{
116    /**
117     * The comparator used to maintain order in this tree map, or
118     * null if it uses the natural ordering of its keys.
119     *
120     * @serial
121     */
122    private final Comparator<? super K> comparator;
123
124    private transient TreeMapEntry<K,V> root = null;
125
126    /**
127     * The number of entries in the tree
128     */
129    private transient int size = 0;
130
131    /**
132     * The number of structural modifications to the tree.
133     */
134    private transient int modCount = 0;
135
136    /**
137     * Constructs a new, empty tree map, using the natural ordering of its
138     * keys.  All keys inserted into the map must implement the {@link
139     * Comparable} interface.  Furthermore, all such keys must be
140     * <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
141     * a {@code ClassCastException} for any keys {@code k1} and
142     * {@code k2} in the map.  If the user attempts to put a key into the
143     * map that violates this constraint (for example, the user attempts to
144     * put a string key into a map whose keys are integers), the
145     * {@code put(Object key, Object value)} call will throw a
146     * {@code ClassCastException}.
147     */
148    public TreeMap() {
149        comparator = null;
150    }
151
152    /**
153     * Constructs a new, empty tree map, ordered according to the given
154     * comparator.  All keys inserted into the map must be <em>mutually
155     * comparable</em> by the given comparator: {@code comparator.compare(k1,
156     * k2)} must not throw a {@code ClassCastException} for any keys
157     * {@code k1} and {@code k2} in the map.  If the user attempts to put
158     * a key into the map that violates this constraint, the {@code put(Object
159     * key, Object value)} call will throw a
160     * {@code ClassCastException}.
161     *
162     * @param comparator the comparator that will be used to order this map.
163     *        If {@code null}, the {@linkplain Comparable natural
164     *        ordering} of the keys will be used.
165     */
166    public TreeMap(Comparator<? super K> comparator) {
167        this.comparator = comparator;
168    }
169
170    /**
171     * Constructs a new tree map containing the same mappings as the given
172     * map, ordered according to the <em>natural ordering</em> of its keys.
173     * All keys inserted into the new map must implement the {@link
174     * Comparable} interface.  Furthermore, all such keys must be
175     * <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
176     * a {@code ClassCastException} for any keys {@code k1} and
177     * {@code k2} in the map.  This method runs in n*log(n) time.
178     *
179     * @param  m the map whose mappings are to be placed in this map
180     * @throws ClassCastException if the keys in m are not {@link Comparable},
181     *         or are not mutually comparable
182     * @throws NullPointerException if the specified map is null
183     */
184    public TreeMap(Map<? extends K, ? extends V> m) {
185        comparator = null;
186        putAll(m);
187    }
188
189    /**
190     * Constructs a new tree map containing the same mappings and
191     * using the same ordering as the specified sorted map.  This
192     * method runs in linear time.
193     *
194     * @param  m the sorted map whose mappings are to be placed in this map,
195     *         and whose comparator is to be used to sort this map
196     * @throws NullPointerException if the specified map is null
197     */
198    public TreeMap(SortedMap<K, ? extends V> m) {
199        comparator = m.comparator();
200        try {
201            buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
202        } catch (java.io.IOException cannotHappen) {
203        } catch (ClassNotFoundException cannotHappen) {
204        }
205    }
206
207
208    // Query Operations
209
210    /**
211     * Returns the number of key-value mappings in this map.
212     *
213     * @return the number of key-value mappings in this map
214     */
215    public int size() {
216        return size;
217    }
218
219    /**
220     * Returns {@code true} if this map contains a mapping for the specified
221     * key.
222     *
223     * @param key key whose presence in this map is to be tested
224     * @return {@code true} if this map contains a mapping for the
225     *         specified key
226     * @throws ClassCastException if the specified key cannot be compared
227     *         with the keys currently in the map
228     * @throws NullPointerException if the specified key is null
229     *         and this map uses natural ordering, or its comparator
230     *         does not permit null keys
231     */
232    public boolean containsKey(Object key) {
233        return getEntry(key) != null;
234    }
235
236    /**
237     * Returns {@code true} if this map maps one or more keys to the
238     * specified value.  More formally, returns {@code true} if and only if
239     * this map contains at least one mapping to a value {@code v} such
240     * that {@code (value==null ? v==null : value.equals(v))}.  This
241     * operation will probably require time linear in the map size for
242     * most implementations.
243     *
244     * @param value value whose presence in this map is to be tested
245     * @return {@code true} if a mapping to {@code value} exists;
246     *         {@code false} otherwise
247     * @since 1.2
248     */
249    public boolean containsValue(Object value) {
250        for (TreeMapEntry<K,V> e = getFirstEntry(); e != null; e = successor(e))
251            if (valEquals(value, e.value))
252                return true;
253        return false;
254    }
255
256    /**
257     * Returns the value to which the specified key is mapped,
258     * or {@code null} if this map contains no mapping for the key.
259     *
260     * <p>More formally, if this map contains a mapping from a key
261     * {@code k} to a value {@code v} such that {@code key} compares
262     * equal to {@code k} according to the map's ordering, then this
263     * method returns {@code v}; otherwise it returns {@code null}.
264     * (There can be at most one such mapping.)
265     *
266     * <p>A return value of {@code null} does not <em>necessarily</em>
267     * indicate that the map contains no mapping for the key; it's also
268     * possible that the map explicitly maps the key to {@code null}.
269     * The {@link #containsKey containsKey} operation may be used to
270     * distinguish these two cases.
271     *
272     * @throws ClassCastException if the specified key cannot be compared
273     *         with the keys currently in the map
274     * @throws NullPointerException if the specified key is null
275     *         and this map uses natural ordering, or its comparator
276     *         does not permit null keys
277     */
278    public V get(Object key) {
279        TreeMapEntry<K,V> p = getEntry(key);
280        return (p==null ? null : p.value);
281    }
282
283    public Comparator<? super K> comparator() {
284        return comparator;
285    }
286
287    /**
288     * @throws NoSuchElementException {@inheritDoc}
289     */
290    public K firstKey() {
291        return key(getFirstEntry());
292    }
293
294    /**
295     * @throws NoSuchElementException {@inheritDoc}
296     */
297    public K lastKey() {
298        return key(getLastEntry());
299    }
300
301    /**
302     * Copies all of the mappings from the specified map to this map.
303     * These mappings replace any mappings that this map had for any
304     * of the keys currently in the specified map.
305     *
306     * @param  map mappings to be stored in this map
307     * @throws ClassCastException if the class of a key or value in
308     *         the specified map prevents it from being stored in this map
309     * @throws NullPointerException if the specified map is null or
310     *         the specified map contains a null key and this map does not
311     *         permit null keys
312     */
313    public void putAll(Map<? extends K, ? extends V> map) {
314        int mapSize = map.size();
315        if (size==0 && mapSize!=0 && map instanceof SortedMap) {
316            Comparator<?> c = ((SortedMap<?,?>)map).comparator();
317            if (c == comparator || (c != null && c.equals(comparator))) {
318                ++modCount;
319                try {
320                    buildFromSorted(mapSize, map.entrySet().iterator(),
321                                    null, null);
322                } catch (java.io.IOException cannotHappen) {
323                } catch (ClassNotFoundException cannotHappen) {
324                }
325                return;
326            }
327        }
328        super.putAll(map);
329    }
330
331    /**
332     * Returns this map's entry for the given key, or {@code null} if the map
333     * does not contain an entry for the key.
334     *
335     * @return this map's entry for the given key, or {@code null} if the map
336     *         does not contain an entry for the key
337     * @throws ClassCastException if the specified key cannot be compared
338     *         with the keys currently in the map
339     * @throws NullPointerException if the specified key is null
340     *         and this map uses natural ordering, or its comparator
341     *         does not permit null keys
342     */
343    final TreeMapEntry<K,V> getEntry(Object key) {
344        // Offload comparator-based version for sake of performance
345        if (comparator != null)
346            return getEntryUsingComparator(key);
347        if (key == null)
348            throw new NullPointerException();
349        @SuppressWarnings("unchecked")
350            Comparable<? super K> k = (Comparable<? super K>) key;
351        TreeMapEntry<K,V> p = root;
352        while (p != null) {
353            int cmp = k.compareTo(p.key);
354            if (cmp < 0)
355                p = p.left;
356            else if (cmp > 0)
357                p = p.right;
358            else
359                return p;
360        }
361        return null;
362    }
363
364    /**
365     * Version of getEntry using comparator. Split off from getEntry
366     * for performance. (This is not worth doing for most methods,
367     * that are less dependent on comparator performance, but is
368     * worthwhile here.)
369     */
370    final TreeMapEntry<K,V> getEntryUsingComparator(Object key) {
371        @SuppressWarnings("unchecked")
372            K k = (K) key;
373        Comparator<? super K> cpr = comparator;
374        if (cpr != null) {
375            TreeMapEntry<K,V> p = root;
376            while (p != null) {
377                int cmp = cpr.compare(k, p.key);
378                if (cmp < 0)
379                    p = p.left;
380                else if (cmp > 0)
381                    p = p.right;
382                else
383                    return p;
384            }
385        }
386        return null;
387    }
388
389    /**
390     * Gets the entry corresponding to the specified key; if no such entry
391     * exists, returns the entry for the least key greater than the specified
392     * key; if no such entry exists (i.e., the greatest key in the Tree is less
393     * than the specified key), returns {@code null}.
394     */
395    final TreeMapEntry<K,V> getCeilingEntry(K key) {
396        TreeMapEntry<K,V> p = root;
397        while (p != null) {
398            int cmp = compare(key, p.key);
399            if (cmp < 0) {
400                if (p.left != null)
401                    p = p.left;
402                else
403                    return p;
404            } else if (cmp > 0) {
405                if (p.right != null) {
406                    p = p.right;
407                } else {
408                    TreeMapEntry<K,V> parent = p.parent;
409                    TreeMapEntry<K,V> ch = p;
410                    while (parent != null && ch == parent.right) {
411                        ch = parent;
412                        parent = parent.parent;
413                    }
414                    return parent;
415                }
416            } else
417                return p;
418        }
419        return null;
420    }
421
422    /**
423     * Gets the entry corresponding to the specified key; if no such entry
424     * exists, returns the entry for the greatest key less than the specified
425     * key; if no such entry exists, returns {@code null}.
426     */
427    final TreeMapEntry<K,V> getFloorEntry(K key) {
428        TreeMapEntry<K,V> p = root;
429        while (p != null) {
430            int cmp = compare(key, p.key);
431            if (cmp > 0) {
432                if (p.right != null)
433                    p = p.right;
434                else
435                    return p;
436            } else if (cmp < 0) {
437                if (p.left != null) {
438                    p = p.left;
439                } else {
440                    TreeMapEntry<K,V> parent = p.parent;
441                    TreeMapEntry<K,V> ch = p;
442                    while (parent != null && ch == parent.left) {
443                        ch = parent;
444                        parent = parent.parent;
445                    }
446                    return parent;
447                }
448            } else
449                return p;
450
451        }
452        return null;
453    }
454
455    /**
456     * Gets the entry for the least key greater than the specified
457     * key; if no such entry exists, returns the entry for the least
458     * key greater than the specified key; if no such entry exists
459     * returns {@code null}.
460     */
461    final TreeMapEntry<K,V> getHigherEntry(K key) {
462        TreeMapEntry<K,V> p = root;
463        while (p != null) {
464            int cmp = compare(key, p.key);
465            if (cmp < 0) {
466                if (p.left != null)
467                    p = p.left;
468                else
469                    return p;
470            } else {
471                if (p.right != null) {
472                    p = p.right;
473                } else {
474                    TreeMapEntry<K,V> parent = p.parent;
475                    TreeMapEntry<K,V> ch = p;
476                    while (parent != null && ch == parent.right) {
477                        ch = parent;
478                        parent = parent.parent;
479                    }
480                    return parent;
481                }
482            }
483        }
484        return null;
485    }
486
487    /**
488     * Returns the entry for the greatest key less than the specified key; if
489     * no such entry exists (i.e., the least key in the Tree is greater than
490     * the specified key), returns {@code null}.
491     */
492    final TreeMapEntry<K,V> getLowerEntry(K key) {
493        TreeMapEntry<K,V> p = root;
494        while (p != null) {
495            int cmp = compare(key, p.key);
496            if (cmp > 0) {
497                if (p.right != null)
498                    p = p.right;
499                else
500                    return p;
501            } else {
502                if (p.left != null) {
503                    p = p.left;
504                } else {
505                    TreeMapEntry<K,V> parent = p.parent;
506                    TreeMapEntry<K,V> ch = p;
507                    while (parent != null && ch == parent.left) {
508                        ch = parent;
509                        parent = parent.parent;
510                    }
511                    return parent;
512                }
513            }
514        }
515        return null;
516    }
517
518    /**
519     * Associates the specified value with the specified key in this map.
520     * If the map previously contained a mapping for the key, the old
521     * value is replaced.
522     *
523     * @param key key with which the specified value is to be associated
524     * @param value value to be associated with the specified key
525     *
526     * @return the previous value associated with {@code key}, or
527     *         {@code null} if there was no mapping for {@code key}.
528     *         (A {@code null} return can also indicate that the map
529     *         previously associated {@code null} with {@code key}.)
530     * @throws ClassCastException if the specified key cannot be compared
531     *         with the keys currently in the map
532     * @throws NullPointerException if the specified key is null
533     *         and this map uses natural ordering, or its comparator
534     *         does not permit null keys
535     */
536    public V put(K key, V value) {
537        TreeMapEntry<K,V> t = root;
538        if (t == null) {
539            // We could just call compare(key, key) for its side effect of checking the type and
540            // nullness of the input key. However, several applications seem to have written comparators
541            // that only expect to be called on elements that aren't equal to each other (after
542            // making assumptions about the domain of the map). Clearly, such comparators are bogus
543            // because get() would never work, but TreeSets are frequently used for sorting a set
544            // of distinct elements.
545            //
546            // As a temporary work around, we perform the null & instanceof checks by hand so that
547            // we can guarantee that elements are never compared against themselves.
548            //
549            // compare(key, key);
550            //
551            // **** THIS CHANGE WILL BE REVERTED IN A FUTURE ANDROID RELEASE ****
552            if (comparator != null) {
553                if (key == null) {
554                    comparator.compare(key, key);
555                }
556            } else {
557                if (key == null) {
558                    throw new NullPointerException("key == null");
559                } else if (!(key instanceof Comparable)) {
560                    throw new ClassCastException(
561                            "Cannot cast" + key.getClass().getName() + " to Comparable.");
562                }
563            }
564
565            root = new TreeMapEntry<>(key, value, null);
566            size = 1;
567            modCount++;
568            return null;
569        }
570        int cmp;
571        TreeMapEntry<K,V> parent;
572        // split comparator and comparable paths
573        Comparator<? super K> cpr = comparator;
574        if (cpr != null) {
575            do {
576                parent = t;
577                cmp = cpr.compare(key, t.key);
578                if (cmp < 0)
579                    t = t.left;
580                else if (cmp > 0)
581                    t = t.right;
582                else
583                    return t.setValue(value);
584            } while (t != null);
585        }
586        else {
587            if (key == null)
588                throw new NullPointerException();
589            @SuppressWarnings("unchecked")
590                Comparable<? super K> k = (Comparable<? super K>) key;
591            do {
592                parent = t;
593                cmp = k.compareTo(t.key);
594                if (cmp < 0)
595                    t = t.left;
596                else if (cmp > 0)
597                    t = t.right;
598                else
599                    return t.setValue(value);
600            } while (t != null);
601        }
602        TreeMapEntry<K,V> e = new TreeMapEntry<>(key, value, parent);
603        if (cmp < 0)
604            parent.left = e;
605        else
606            parent.right = e;
607        fixAfterInsertion(e);
608        size++;
609        modCount++;
610        return null;
611    }
612
613    /**
614     * Removes the mapping for this key from this TreeMap if present.
615     *
616     * @param  key key for which mapping should be removed
617     * @return the previous value associated with {@code key}, or
618     *         {@code null} if there was no mapping for {@code key}.
619     *         (A {@code null} return can also indicate that the map
620     *         previously associated {@code null} with {@code key}.)
621     * @throws ClassCastException if the specified key cannot be compared
622     *         with the keys currently in the map
623     * @throws NullPointerException if the specified key is null
624     *         and this map uses natural ordering, or its comparator
625     *         does not permit null keys
626     */
627    public V remove(Object key) {
628        TreeMapEntry<K,V> p = getEntry(key);
629        if (p == null)
630            return null;
631
632        V oldValue = p.value;
633        deleteEntry(p);
634        return oldValue;
635    }
636
637    /**
638     * Removes all of the mappings from this map.
639     * The map will be empty after this call returns.
640     */
641    public void clear() {
642        modCount++;
643        size = 0;
644        root = null;
645    }
646
647    /**
648     * Returns a shallow copy of this {@code TreeMap} instance. (The keys and
649     * values themselves are not cloned.)
650     *
651     * @return a shallow copy of this map
652     */
653    public Object clone() {
654        TreeMap<?,?> clone;
655        try {
656            clone = (TreeMap<?,?>) super.clone();
657        } catch (CloneNotSupportedException e) {
658            throw new InternalError(e);
659        }
660
661        // Put clone into "virgin" state (except for comparator)
662        clone.root = null;
663        clone.size = 0;
664        clone.modCount = 0;
665        clone.entrySet = null;
666        clone.navigableKeySet = null;
667        clone.descendingMap = null;
668
669        // Initialize clone with our mappings
670        try {
671            clone.buildFromSorted(size, entrySet().iterator(), null, null);
672        } catch (java.io.IOException cannotHappen) {
673        } catch (ClassNotFoundException cannotHappen) {
674        }
675
676        return clone;
677    }
678
679    // NavigableMap API methods
680
681    /**
682     * @since 1.6
683     */
684    public Map.Entry<K,V> firstEntry() {
685        return exportEntry(getFirstEntry());
686    }
687
688    /**
689     * @since 1.6
690     */
691    public Map.Entry<K,V> lastEntry() {
692        return exportEntry(getLastEntry());
693    }
694
695    /**
696     * @since 1.6
697     */
698    public Map.Entry<K,V> pollFirstEntry() {
699        TreeMapEntry<K,V> p = getFirstEntry();
700        Map.Entry<K,V> result = exportEntry(p);
701        if (p != null)
702            deleteEntry(p);
703        return result;
704    }
705
706    /**
707     * @since 1.6
708     */
709    public Map.Entry<K,V> pollLastEntry() {
710        TreeMapEntry<K,V> p = getLastEntry();
711        Map.Entry<K,V> result = exportEntry(p);
712        if (p != null)
713            deleteEntry(p);
714        return result;
715    }
716
717    /**
718     * @throws ClassCastException {@inheritDoc}
719     * @throws NullPointerException if the specified key is null
720     *         and this map uses natural ordering, or its comparator
721     *         does not permit null keys
722     * @since 1.6
723     */
724    public Map.Entry<K,V> lowerEntry(K key) {
725        return exportEntry(getLowerEntry(key));
726    }
727
728    /**
729     * @throws ClassCastException {@inheritDoc}
730     * @throws NullPointerException if the specified key is null
731     *         and this map uses natural ordering, or its comparator
732     *         does not permit null keys
733     * @since 1.6
734     */
735    public K lowerKey(K key) {
736        return keyOrNull(getLowerEntry(key));
737    }
738
739    /**
740     * @throws ClassCastException {@inheritDoc}
741     * @throws NullPointerException if the specified key is null
742     *         and this map uses natural ordering, or its comparator
743     *         does not permit null keys
744     * @since 1.6
745     */
746    public Map.Entry<K,V> floorEntry(K key) {
747        return exportEntry(getFloorEntry(key));
748    }
749
750    /**
751     * @throws ClassCastException {@inheritDoc}
752     * @throws NullPointerException if the specified key is null
753     *         and this map uses natural ordering, or its comparator
754     *         does not permit null keys
755     * @since 1.6
756     */
757    public K floorKey(K key) {
758        return keyOrNull(getFloorEntry(key));
759    }
760
761    /**
762     * @throws ClassCastException {@inheritDoc}
763     * @throws NullPointerException if the specified key is null
764     *         and this map uses natural ordering, or its comparator
765     *         does not permit null keys
766     * @since 1.6
767     */
768    public Map.Entry<K,V> ceilingEntry(K key) {
769        return exportEntry(getCeilingEntry(key));
770    }
771
772    /**
773     * @throws ClassCastException {@inheritDoc}
774     * @throws NullPointerException if the specified key is null
775     *         and this map uses natural ordering, or its comparator
776     *         does not permit null keys
777     * @since 1.6
778     */
779    public K ceilingKey(K key) {
780        return keyOrNull(getCeilingEntry(key));
781    }
782
783    /**
784     * @throws ClassCastException {@inheritDoc}
785     * @throws NullPointerException if the specified key is null
786     *         and this map uses natural ordering, or its comparator
787     *         does not permit null keys
788     * @since 1.6
789     */
790    public Map.Entry<K,V> higherEntry(K key) {
791        return exportEntry(getHigherEntry(key));
792    }
793
794    /**
795     * @throws ClassCastException {@inheritDoc}
796     * @throws NullPointerException if the specified key is null
797     *         and this map uses natural ordering, or its comparator
798     *         does not permit null keys
799     * @since 1.6
800     */
801    public K higherKey(K key) {
802        return keyOrNull(getHigherEntry(key));
803    }
804
805    // Views
806
807    /**
808     * Fields initialized to contain an instance of the entry set view
809     * the first time this view is requested.  Views are stateless, so
810     * there's no reason to create more than one.
811     */
812    private transient EntrySet entrySet = null;
813    private transient KeySet<K> navigableKeySet = null;
814    private transient NavigableMap<K,V> descendingMap = null;
815
816    /**
817     * Returns a {@link Set} view of the keys contained in this map.
818     *
819     * <p>The set's iterator returns the keys in ascending order.
820     * The set's spliterator is
821     * <em><a href="Spliterator.html#binding">late-binding</a></em>,
822     * <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED}
823     * and {@link Spliterator#ORDERED} with an encounter order that is ascending
824     * key order.  The spliterator's comparator (see
825     * {@link java.util.Spliterator#getComparator()}) is {@code null} if
826     * the tree map's comparator (see {@link #comparator()}) is {@code null}.
827     * Otherwise, the spliterator's comparator is the same as or imposes the
828     * same total ordering as the tree map's comparator.
829     *
830     * <p>The set is backed by the map, so changes to the map are
831     * reflected in the set, and vice-versa.  If the map is modified
832     * while an iteration over the set is in progress (except through
833     * the iterator's own {@code remove} operation), the results of
834     * the iteration are undefined.  The set supports element removal,
835     * which removes the corresponding mapping from the map, via the
836     * {@code Iterator.remove}, {@code Set.remove},
837     * {@code removeAll}, {@code retainAll}, and {@code clear}
838     * operations.  It does not support the {@code add} or {@code addAll}
839     * operations.
840     */
841    public Set<K> keySet() {
842        return navigableKeySet();
843    }
844
845    /**
846     * @since 1.6
847     */
848    public NavigableSet<K> navigableKeySet() {
849        KeySet<K> nks = navigableKeySet;
850        return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
851    }
852
853    /**
854     * @since 1.6
855     */
856    public NavigableSet<K> descendingKeySet() {
857        return descendingMap().navigableKeySet();
858    }
859
860    /**
861     * Returns a {@link Collection} view of the values contained in this map.
862     *
863     * <p>The collection's iterator returns the values in ascending order
864     * of the corresponding keys. The collection's spliterator is
865     * <em><a href="Spliterator.html#binding">late-binding</a></em>,
866     * <em>fail-fast</em>, and additionally reports {@link Spliterator#ORDERED}
867     * with an encounter order that is ascending order of the corresponding
868     * keys.
869     *
870     * <p>The collection is backed by the map, so changes to the map are
871     * reflected in the collection, and vice-versa.  If the map is
872     * modified while an iteration over the collection is in progress
873     * (except through the iterator's own {@code remove} operation),
874     * the results of the iteration are undefined.  The collection
875     * supports element removal, which removes the corresponding
876     * mapping from the map, via the {@code Iterator.remove},
877     * {@code Collection.remove}, {@code removeAll},
878     * {@code retainAll} and {@code clear} operations.  It does not
879     * support the {@code add} or {@code addAll} operations.
880     */
881    public Collection<V> values() {
882        Collection<V> vs = values;
883        return (vs != null) ? vs : (values = new Values());
884    }
885
886    /**
887     * Returns a {@link Set} view of the mappings contained in this map.
888     *
889     * <p>The set's iterator returns the entries in ascending key order. The
890     * sets's spliterator is
891     * <em><a href="Spliterator.html#binding">late-binding</a></em>,
892     * <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED} and
893     * {@link Spliterator#ORDERED} with an encounter order that is ascending key
894     * order.
895     *
896     * <p>The set is backed by the map, so changes to the map are
897     * reflected in the set, and vice-versa.  If the map is modified
898     * while an iteration over the set is in progress (except through
899     * the iterator's own {@code remove} operation, or through the
900     * {@code setValue} operation on a map entry returned by the
901     * iterator) the results of the iteration are undefined.  The set
902     * supports element removal, which removes the corresponding
903     * mapping from the map, via the {@code Iterator.remove},
904     * {@code Set.remove}, {@code removeAll}, {@code retainAll} and
905     * {@code clear} operations.  It does not support the
906     * {@code add} or {@code addAll} operations.
907     */
908    public Set<Map.Entry<K,V>> entrySet() {
909        EntrySet es = entrySet;
910        return (es != null) ? es : (entrySet = new EntrySet());
911    }
912
913    /**
914     * @since 1.6
915     */
916    public NavigableMap<K, V> descendingMap() {
917        NavigableMap<K, V> km = descendingMap;
918        return (km != null) ? km :
919            (descendingMap = new DescendingSubMap<>(this,
920                                                    true, null, true,
921                                                    true, null, true));
922    }
923
924    /**
925     * @throws ClassCastException       {@inheritDoc}
926     * @throws NullPointerException if {@code fromKey} or {@code toKey} is
927     *         null and this map uses natural ordering, or its comparator
928     *         does not permit null keys
929     * @throws IllegalArgumentException {@inheritDoc}
930     * @since 1.6
931     */
932    public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
933                                    K toKey,   boolean toInclusive) {
934        return new AscendingSubMap<>(this,
935                                     false, fromKey, fromInclusive,
936                                     false, toKey,   toInclusive);
937    }
938
939    /**
940     * @throws ClassCastException       {@inheritDoc}
941     * @throws NullPointerException if {@code toKey} is null
942     *         and this map uses natural ordering, or its comparator
943     *         does not permit null keys
944     * @throws IllegalArgumentException {@inheritDoc}
945     * @since 1.6
946     */
947    public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
948        return new AscendingSubMap<>(this,
949                                     true,  null,  true,
950                                     false, toKey, inclusive);
951    }
952
953    /**
954     * @throws ClassCastException       {@inheritDoc}
955     * @throws NullPointerException if {@code fromKey} is null
956     *         and this map uses natural ordering, or its comparator
957     *         does not permit null keys
958     * @throws IllegalArgumentException {@inheritDoc}
959     * @since 1.6
960     */
961    public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
962        return new AscendingSubMap<>(this,
963                                     false, fromKey, inclusive,
964                                     true,  null,    true);
965    }
966
967    /**
968     * @throws ClassCastException       {@inheritDoc}
969     * @throws NullPointerException if {@code fromKey} or {@code toKey} is
970     *         null and this map uses natural ordering, or its comparator
971     *         does not permit null keys
972     * @throws IllegalArgumentException {@inheritDoc}
973     */
974    public SortedMap<K,V> subMap(K fromKey, K toKey) {
975        return subMap(fromKey, true, toKey, false);
976    }
977
978    /**
979     * @throws ClassCastException       {@inheritDoc}
980     * @throws NullPointerException if {@code toKey} is null
981     *         and this map uses natural ordering, or its comparator
982     *         does not permit null keys
983     * @throws IllegalArgumentException {@inheritDoc}
984     */
985    public SortedMap<K,V> headMap(K toKey) {
986        return headMap(toKey, false);
987    }
988
989    /**
990     * @throws ClassCastException       {@inheritDoc}
991     * @throws NullPointerException if {@code fromKey} is null
992     *         and this map uses natural ordering, or its comparator
993     *         does not permit null keys
994     * @throws IllegalArgumentException {@inheritDoc}
995     */
996    public SortedMap<K,V> tailMap(K fromKey) {
997        return tailMap(fromKey, true);
998    }
999
1000    @Override
1001    public void forEach(BiConsumer<? super K, ? super V> action) {
1002        Objects.requireNonNull(action);
1003        int expectedModCount = modCount;
1004        for (TreeMapEntry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
1005            action.accept(e.key, e.value);
1006
1007            if (expectedModCount != modCount) {
1008                throw new ConcurrentModificationException();
1009            }
1010        }
1011    }
1012
1013    // View class support
1014
1015    class Values extends AbstractCollection<V> {
1016        public Iterator<V> iterator() {
1017            return new ValueIterator(getFirstEntry());
1018        }
1019
1020        public int size() {
1021            return TreeMap.this.size();
1022        }
1023
1024        public boolean contains(Object o) {
1025            return TreeMap.this.containsValue(o);
1026        }
1027
1028        public boolean remove(Object o) {
1029            for (TreeMapEntry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
1030                if (valEquals(e.getValue(), o)) {
1031                    deleteEntry(e);
1032                    return true;
1033                }
1034            }
1035            return false;
1036        }
1037
1038        public void clear() {
1039            TreeMap.this.clear();
1040        }
1041
1042        public Spliterator<V> spliterator() {
1043            return new ValueSpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
1044        }
1045    }
1046
1047    class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1048        public Iterator<Map.Entry<K,V>> iterator() {
1049            return new EntryIterator(getFirstEntry());
1050        }
1051
1052        public boolean contains(Object o) {
1053            if (!(o instanceof Map.Entry))
1054                return false;
1055            Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1056            V value = entry.getValue();
1057            TreeMapEntry<K,V> p = getEntry(entry.getKey());
1058            return p != null && valEquals(p.getValue(), value);
1059        }
1060
1061        public boolean remove(Object o) {
1062            if (!(o instanceof Map.Entry))
1063                return false;
1064            Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1065            V value = entry.getValue();
1066            TreeMapEntry<K,V> p = getEntry(entry.getKey());
1067            if (p != null && valEquals(p.getValue(), value)) {
1068                deleteEntry(p);
1069                return true;
1070            }
1071            return false;
1072        }
1073
1074        public int size() {
1075            return TreeMap.this.size();
1076        }
1077
1078        public void clear() {
1079            TreeMap.this.clear();
1080        }
1081
1082        public Spliterator<Map.Entry<K,V>> spliterator() {
1083            return new EntrySpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
1084        }
1085    }
1086
1087    /*
1088     * Unlike Values and EntrySet, the KeySet class is static,
1089     * delegating to a NavigableMap to allow use by SubMaps, which
1090     * outweighs the ugliness of needing type-tests for the following
1091     * Iterator methods that are defined appropriately in main versus
1092     * submap classes.
1093     */
1094
1095    Iterator<K> keyIterator() {
1096        return new KeyIterator(getFirstEntry());
1097    }
1098
1099    Iterator<K> descendingKeyIterator() {
1100        return new DescendingKeyIterator(getLastEntry());
1101    }
1102
1103    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
1104        private final NavigableMap<E, ?> m;
1105        KeySet(NavigableMap<E,?> map) { m = map; }
1106
1107        public Iterator<E> iterator() {
1108            if (m instanceof TreeMap)
1109                return ((TreeMap<E,?>)m).keyIterator();
1110            else
1111                return ((TreeMap.NavigableSubMap<E,?>)m).keyIterator();
1112        }
1113
1114        public Iterator<E> descendingIterator() {
1115            if (m instanceof TreeMap)
1116                return ((TreeMap<E,?>)m).descendingKeyIterator();
1117            else
1118                return ((TreeMap.NavigableSubMap<E,?>)m).descendingKeyIterator();
1119        }
1120
1121        public int size() { return m.size(); }
1122        public boolean isEmpty() { return m.isEmpty(); }
1123        public boolean contains(Object o) { return m.containsKey(o); }
1124        public void clear() { m.clear(); }
1125        public E lower(E e) { return m.lowerKey(e); }
1126        public E floor(E e) { return m.floorKey(e); }
1127        public E ceiling(E e) { return m.ceilingKey(e); }
1128        public E higher(E e) { return m.higherKey(e); }
1129        public E first() { return m.firstKey(); }
1130        public E last() { return m.lastKey(); }
1131        public Comparator<? super E> comparator() { return m.comparator(); }
1132        public E pollFirst() {
1133            Map.Entry<E,?> e = m.pollFirstEntry();
1134            return (e == null) ? null : e.getKey();
1135        }
1136        public E pollLast() {
1137            Map.Entry<E,?> e = m.pollLastEntry();
1138            return (e == null) ? null : e.getKey();
1139        }
1140        public boolean remove(Object o) {
1141            int oldSize = size();
1142            m.remove(o);
1143            return size() != oldSize;
1144        }
1145        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
1146                                      E toElement,   boolean toInclusive) {
1147            return new KeySet<>(m.subMap(fromElement, fromInclusive,
1148                                          toElement,   toInclusive));
1149        }
1150        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1151            return new KeySet<>(m.headMap(toElement, inclusive));
1152        }
1153        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1154            return new KeySet<>(m.tailMap(fromElement, inclusive));
1155        }
1156        public SortedSet<E> subSet(E fromElement, E toElement) {
1157            return subSet(fromElement, true, toElement, false);
1158        }
1159        public SortedSet<E> headSet(E toElement) {
1160            return headSet(toElement, false);
1161        }
1162        public SortedSet<E> tailSet(E fromElement) {
1163            return tailSet(fromElement, true);
1164        }
1165        public NavigableSet<E> descendingSet() {
1166            return new KeySet<>(m.descendingMap());
1167        }
1168
1169        public Spliterator<E> spliterator() {
1170            return keySpliteratorFor(m);
1171        }
1172    }
1173
1174    /**
1175     * Base class for TreeMap Iterators
1176     */
1177    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1178        TreeMapEntry<K,V> next;
1179        TreeMapEntry<K,V> lastReturned;
1180        int expectedModCount;
1181
1182        PrivateEntryIterator(TreeMapEntry<K,V> first) {
1183            expectedModCount = modCount;
1184            lastReturned = null;
1185            next = first;
1186        }
1187
1188        public final boolean hasNext() {
1189            return next != null;
1190        }
1191
1192        final TreeMapEntry<K,V> nextEntry() {
1193            TreeMapEntry<K,V> e = next;
1194            if (e == null)
1195                throw new NoSuchElementException();
1196            if (modCount != expectedModCount)
1197                throw new ConcurrentModificationException();
1198            next = successor(e);
1199            lastReturned = e;
1200            return e;
1201        }
1202
1203        final TreeMapEntry<K,V> prevEntry() {
1204            TreeMapEntry<K,V> e = next;
1205            if (e == null)
1206                throw new NoSuchElementException();
1207            if (modCount != expectedModCount)
1208                throw new ConcurrentModificationException();
1209            next = predecessor(e);
1210            lastReturned = e;
1211            return e;
1212        }
1213
1214        public void remove() {
1215            if (lastReturned == null)
1216                throw new IllegalStateException();
1217            if (modCount != expectedModCount)
1218                throw new ConcurrentModificationException();
1219            // deleted entries are replaced by their successors
1220            if (lastReturned.left != null && lastReturned.right != null)
1221                next = lastReturned;
1222            deleteEntry(lastReturned);
1223            expectedModCount = modCount;
1224            lastReturned = null;
1225        }
1226    }
1227
1228    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1229        EntryIterator(TreeMapEntry<K,V> first) {
1230            super(first);
1231        }
1232        public Map.Entry<K,V> next() {
1233            return nextEntry();
1234        }
1235    }
1236
1237    final class ValueIterator extends PrivateEntryIterator<V> {
1238        ValueIterator(TreeMapEntry<K,V> first) {
1239            super(first);
1240        }
1241        public V next() {
1242            return nextEntry().value;
1243        }
1244    }
1245
1246    final class KeyIterator extends PrivateEntryIterator<K> {
1247        KeyIterator(TreeMapEntry<K,V> first) {
1248            super(first);
1249        }
1250        public K next() {
1251            return nextEntry().key;
1252        }
1253    }
1254
1255    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1256        DescendingKeyIterator(TreeMapEntry<K,V> first) {
1257            super(first);
1258        }
1259        public K next() {
1260            return prevEntry().key;
1261        }
1262        public void remove() {
1263            if (lastReturned == null)
1264                throw new IllegalStateException();
1265            if (modCount != expectedModCount)
1266                throw new ConcurrentModificationException();
1267            deleteEntry(lastReturned);
1268            lastReturned = null;
1269            expectedModCount = modCount;
1270        }
1271    }
1272
1273    // Little utilities
1274
1275    /**
1276     * Compares two keys using the correct comparison method for this TreeMap.
1277     */
1278    @SuppressWarnings("unchecked")
1279    final int compare(Object k1, Object k2) {
1280        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1281            : comparator.compare((K)k1, (K)k2);
1282    }
1283
1284    /**
1285     * Test two values for equality.  Differs from o1.equals(o2) only in
1286     * that it copes with {@code null} o1 properly.
1287     */
1288    static final boolean valEquals(Object o1, Object o2) {
1289        return (o1==null ? o2==null : o1.equals(o2));
1290    }
1291
1292    /**
1293     * Return SimpleImmutableEntry for entry, or null if null
1294     */
1295    static <K,V> Map.Entry<K,V> exportEntry(TreeMapEntry<K,V> e) {
1296        return (e == null) ? null :
1297            new AbstractMap.SimpleImmutableEntry<>(e);
1298    }
1299
1300    /**
1301     * Return key for entry, or null if null
1302     */
1303    static <K,V> K keyOrNull(TreeMapEntry<K,V> e) {
1304        return (e == null) ? null : e.key;
1305    }
1306
1307    /**
1308     * Returns the key corresponding to the specified Entry.
1309     * @throws NoSuchElementException if the Entry is null
1310     */
1311    static <K> K key(TreeMapEntry<K,?> e) {
1312        if (e==null)
1313            throw new NoSuchElementException();
1314        return e.key;
1315    }
1316
1317
1318    // SubMaps
1319
1320    /**
1321     * Dummy value serving as unmatchable fence key for unbounded
1322     * SubMapIterators
1323     */
1324    private static final Object UNBOUNDED = new Object();
1325
1326    /**
1327     * @serial include
1328     */
1329    abstract static class NavigableSubMap<K,V> extends AbstractMap<K,V>
1330        implements NavigableMap<K,V>, java.io.Serializable {
1331        // Android-changed: Explicitly add a serialVersionUID so that we're serialization
1332        // compatible with the Java-7 version of this class. Several new methods were added
1333        // in Java-8 but none of them have any bearing on the serialized format of the class
1334        // or require any additional state to be preserved.
1335        private static final long serialVersionUID = 2765629423043303731L;
1336
1337        /**
1338         * The backing map.
1339         */
1340        final TreeMap<K,V> m;
1341
1342        /**
1343         * Endpoints are represented as triples (fromStart, lo,
1344         * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1345         * true, then the low (absolute) bound is the start of the
1346         * backing map, and the other values are ignored. Otherwise,
1347         * if loInclusive is true, lo is the inclusive bound, else lo
1348         * is the exclusive bound. Similarly for the upper bound.
1349         */
1350        final K lo, hi;
1351        final boolean fromStart, toEnd;
1352        final boolean loInclusive, hiInclusive;
1353
1354        NavigableSubMap(TreeMap<K,V> m,
1355                        boolean fromStart, K lo, boolean loInclusive,
1356                        boolean toEnd,     K hi, boolean hiInclusive) {
1357            if (!fromStart && !toEnd) {
1358                if (m.compare(lo, hi) > 0)
1359                    throw new IllegalArgumentException("fromKey > toKey");
1360            } else {
1361                if (!fromStart) // type check
1362                    m.compare(lo, lo);
1363                if (!toEnd)
1364                    m.compare(hi, hi);
1365            }
1366
1367            this.m = m;
1368            this.fromStart = fromStart;
1369            this.lo = lo;
1370            this.loInclusive = loInclusive;
1371            this.toEnd = toEnd;
1372            this.hi = hi;
1373            this.hiInclusive = hiInclusive;
1374        }
1375
1376        // internal utilities
1377
1378        final boolean tooLow(Object key) {
1379            if (!fromStart) {
1380                int c = m.compare(key, lo);
1381                if (c < 0 || (c == 0 && !loInclusive))
1382                    return true;
1383            }
1384            return false;
1385        }
1386
1387        final boolean tooHigh(Object key) {
1388            if (!toEnd) {
1389                int c = m.compare(key, hi);
1390                if (c > 0 || (c == 0 && !hiInclusive))
1391                    return true;
1392            }
1393            return false;
1394        }
1395
1396        final boolean inRange(Object key) {
1397            return !tooLow(key) && !tooHigh(key);
1398        }
1399
1400        final boolean inClosedRange(Object key) {
1401            return (fromStart || m.compare(key, lo) >= 0)
1402                && (toEnd || m.compare(hi, key) >= 0);
1403        }
1404
1405        final boolean inRange(Object key, boolean inclusive) {
1406            return inclusive ? inRange(key) : inClosedRange(key);
1407        }
1408
1409        /*
1410         * Absolute versions of relation operations.
1411         * Subclasses map to these using like-named "sub"
1412         * versions that invert senses for descending maps
1413         */
1414
1415        final TreeMapEntry<K,V> absLowest() {
1416            TreeMapEntry<K,V> e =
1417                (fromStart ?  m.getFirstEntry() :
1418                 (loInclusive ? m.getCeilingEntry(lo) :
1419                                m.getHigherEntry(lo)));
1420            return (e == null || tooHigh(e.key)) ? null : e;
1421        }
1422
1423        final TreeMapEntry<K,V> absHighest() {
1424            TreeMapEntry<K,V> e =
1425                (toEnd ?  m.getLastEntry() :
1426                 (hiInclusive ?  m.getFloorEntry(hi) :
1427                                 m.getLowerEntry(hi)));
1428            return (e == null || tooLow(e.key)) ? null : e;
1429        }
1430
1431        final TreeMapEntry<K,V> absCeiling(K key) {
1432            if (tooLow(key))
1433                return absLowest();
1434            TreeMapEntry<K,V> e = m.getCeilingEntry(key);
1435            return (e == null || tooHigh(e.key)) ? null : e;
1436        }
1437
1438        final TreeMapEntry<K,V> absHigher(K key) {
1439            if (tooLow(key))
1440                return absLowest();
1441            TreeMapEntry<K,V> e = m.getHigherEntry(key);
1442            return (e == null || tooHigh(e.key)) ? null : e;
1443        }
1444
1445        final TreeMapEntry<K,V> absFloor(K key) {
1446            if (tooHigh(key))
1447                return absHighest();
1448            TreeMapEntry<K,V> e = m.getFloorEntry(key);
1449            return (e == null || tooLow(e.key)) ? null : e;
1450        }
1451
1452        final TreeMapEntry<K,V> absLower(K key) {
1453            if (tooHigh(key))
1454                return absHighest();
1455            TreeMapEntry<K,V> e = m.getLowerEntry(key);
1456            return (e == null || tooLow(e.key)) ? null : e;
1457        }
1458
1459        /** Returns the absolute high fence for ascending traversal */
1460        final TreeMapEntry<K,V> absHighFence() {
1461            return (toEnd ? null : (hiInclusive ?
1462                                    m.getHigherEntry(hi) :
1463                                    m.getCeilingEntry(hi)));
1464        }
1465
1466        /** Return the absolute low fence for descending traversal  */
1467        final TreeMapEntry<K,V> absLowFence() {
1468            return (fromStart ? null : (loInclusive ?
1469                                        m.getLowerEntry(lo) :
1470                                        m.getFloorEntry(lo)));
1471        }
1472
1473        // Abstract methods defined in ascending vs descending classes
1474        // These relay to the appropriate absolute versions
1475
1476        abstract TreeMapEntry<K,V> subLowest();
1477        abstract TreeMapEntry<K,V> subHighest();
1478        abstract TreeMapEntry<K,V> subCeiling(K key);
1479        abstract TreeMapEntry<K,V> subHigher(K key);
1480        abstract TreeMapEntry<K,V> subFloor(K key);
1481        abstract TreeMapEntry<K,V> subLower(K key);
1482
1483        /** Returns ascending iterator from the perspective of this submap */
1484        abstract Iterator<K> keyIterator();
1485
1486        abstract Spliterator<K> keySpliterator();
1487
1488        /** Returns descending iterator from the perspective of this submap */
1489        abstract Iterator<K> descendingKeyIterator();
1490
1491        // public methods
1492
1493        public boolean isEmpty() {
1494            return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1495        }
1496
1497        public int size() {
1498            return (fromStart && toEnd) ? m.size() : entrySet().size();
1499        }
1500
1501        public final boolean containsKey(Object key) {
1502            return inRange(key) && m.containsKey(key);
1503        }
1504
1505        public final V put(K key, V value) {
1506            if (!inRange(key))
1507                throw new IllegalArgumentException("key out of range");
1508            return m.put(key, value);
1509        }
1510
1511        public final V get(Object key) {
1512            return !inRange(key) ? null :  m.get(key);
1513        }
1514
1515        public final V remove(Object key) {
1516            return !inRange(key) ? null : m.remove(key);
1517        }
1518
1519        public final Map.Entry<K,V> ceilingEntry(K key) {
1520            return exportEntry(subCeiling(key));
1521        }
1522
1523        public final K ceilingKey(K key) {
1524            return keyOrNull(subCeiling(key));
1525        }
1526
1527        public final Map.Entry<K,V> higherEntry(K key) {
1528            return exportEntry(subHigher(key));
1529        }
1530
1531        public final K higherKey(K key) {
1532            return keyOrNull(subHigher(key));
1533        }
1534
1535        public final Map.Entry<K,V> floorEntry(K key) {
1536            return exportEntry(subFloor(key));
1537        }
1538
1539        public final K floorKey(K key) {
1540            return keyOrNull(subFloor(key));
1541        }
1542
1543        public final Map.Entry<K,V> lowerEntry(K key) {
1544            return exportEntry(subLower(key));
1545        }
1546
1547        public final K lowerKey(K key) {
1548            return keyOrNull(subLower(key));
1549        }
1550
1551        public final K firstKey() {
1552            return key(subLowest());
1553        }
1554
1555        public final K lastKey() {
1556            return key(subHighest());
1557        }
1558
1559        public final Map.Entry<K,V> firstEntry() {
1560            return exportEntry(subLowest());
1561        }
1562
1563        public final Map.Entry<K,V> lastEntry() {
1564            return exportEntry(subHighest());
1565        }
1566
1567        public final Map.Entry<K,V> pollFirstEntry() {
1568            TreeMapEntry<K,V> e = subLowest();
1569            Map.Entry<K,V> result = exportEntry(e);
1570            if (e != null)
1571                m.deleteEntry(e);
1572            return result;
1573        }
1574
1575        public final Map.Entry<K,V> pollLastEntry() {
1576            TreeMapEntry<K,V> e = subHighest();
1577            Map.Entry<K,V> result = exportEntry(e);
1578            if (e != null)
1579                m.deleteEntry(e);
1580            return result;
1581        }
1582
1583        // Views
1584        transient NavigableMap<K,V> descendingMapView = null;
1585        transient EntrySetView entrySetView = null;
1586        transient KeySet<K> navigableKeySetView = null;
1587
1588        public final NavigableSet<K> navigableKeySet() {
1589            KeySet<K> nksv = navigableKeySetView;
1590            return (nksv != null) ? nksv :
1591                (navigableKeySetView = new TreeMap.KeySet<>(this));
1592        }
1593
1594        public final Set<K> keySet() {
1595            return navigableKeySet();
1596        }
1597
1598        public NavigableSet<K> descendingKeySet() {
1599            return descendingMap().navigableKeySet();
1600        }
1601
1602        public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1603            return subMap(fromKey, true, toKey, false);
1604        }
1605
1606        public final SortedMap<K,V> headMap(K toKey) {
1607            return headMap(toKey, false);
1608        }
1609
1610        public final SortedMap<K,V> tailMap(K fromKey) {
1611            return tailMap(fromKey, true);
1612        }
1613
1614        // View classes
1615
1616        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1617            private transient int size = -1, sizeModCount;
1618
1619            public int size() {
1620                if (fromStart && toEnd)
1621                    return m.size();
1622                if (size == -1 || sizeModCount != m.modCount) {
1623                    sizeModCount = m.modCount;
1624                    size = 0;
1625                    Iterator<?> i = iterator();
1626                    while (i.hasNext()) {
1627                        size++;
1628                        i.next();
1629                    }
1630                }
1631                return size;
1632            }
1633
1634            public boolean isEmpty() {
1635                TreeMapEntry<K,V> n = absLowest();
1636                return n == null || tooHigh(n.key);
1637            }
1638
1639            public boolean contains(Object o) {
1640                if (!(o instanceof Map.Entry))
1641                    return false;
1642                Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
1643                Object key = entry.getKey();
1644                if (!inRange(key))
1645                    return false;
1646                TreeMapEntry<?, ?> node = m.getEntry(key);
1647                return node != null &&
1648                    valEquals(node.getValue(), entry.getValue());
1649            }
1650
1651            public boolean remove(Object o) {
1652                if (!(o instanceof Map.Entry))
1653                    return false;
1654                Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
1655                Object key = entry.getKey();
1656                if (!inRange(key))
1657                    return false;
1658                TreeMapEntry<K,V> node = m.getEntry(key);
1659                if (node!=null && valEquals(node.getValue(),
1660                                            entry.getValue())) {
1661                    m.deleteEntry(node);
1662                    return true;
1663                }
1664                return false;
1665            }
1666        }
1667
1668        /**
1669         * Iterators for SubMaps
1670         */
1671        abstract class SubMapIterator<T> implements Iterator<T> {
1672            TreeMapEntry<K,V> lastReturned;
1673            TreeMapEntry<K,V> next;
1674            final Object fenceKey;
1675            int expectedModCount;
1676
1677            SubMapIterator(TreeMapEntry<K,V> first,
1678                           TreeMapEntry<K,V> fence) {
1679                expectedModCount = m.modCount;
1680                lastReturned = null;
1681                next = first;
1682                fenceKey = fence == null ? UNBOUNDED : fence.key;
1683            }
1684
1685            public final boolean hasNext() {
1686                return next != null && next.key != fenceKey;
1687            }
1688
1689            final TreeMapEntry<K,V> nextEntry() {
1690                TreeMapEntry<K,V> e = next;
1691                if (e == null || e.key == fenceKey)
1692                    throw new NoSuchElementException();
1693                if (m.modCount != expectedModCount)
1694                    throw new ConcurrentModificationException();
1695                next = successor(e);
1696                lastReturned = e;
1697                return e;
1698            }
1699
1700            final TreeMapEntry<K,V> prevEntry() {
1701                TreeMapEntry<K,V> e = next;
1702                if (e == null || e.key == fenceKey)
1703                    throw new NoSuchElementException();
1704                if (m.modCount != expectedModCount)
1705                    throw new ConcurrentModificationException();
1706                next = predecessor(e);
1707                lastReturned = e;
1708                return e;
1709            }
1710
1711            final void removeAscending() {
1712                if (lastReturned == null)
1713                    throw new IllegalStateException();
1714                if (m.modCount != expectedModCount)
1715                    throw new ConcurrentModificationException();
1716                // deleted entries are replaced by their successors
1717                if (lastReturned.left != null && lastReturned.right != null)
1718                    next = lastReturned;
1719                m.deleteEntry(lastReturned);
1720                lastReturned = null;
1721                expectedModCount = m.modCount;
1722            }
1723
1724            final void removeDescending() {
1725                if (lastReturned == null)
1726                    throw new IllegalStateException();
1727                if (m.modCount != expectedModCount)
1728                    throw new ConcurrentModificationException();
1729                m.deleteEntry(lastReturned);
1730                lastReturned = null;
1731                expectedModCount = m.modCount;
1732            }
1733
1734        }
1735
1736        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1737            SubMapEntryIterator(TreeMapEntry<K,V> first,
1738                                TreeMapEntry<K,V> fence) {
1739                super(first, fence);
1740            }
1741            public Map.Entry<K,V> next() {
1742                return nextEntry();
1743            }
1744            public void remove() {
1745                removeAscending();
1746            }
1747        }
1748
1749        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1750            DescendingSubMapEntryIterator(TreeMapEntry<K,V> last,
1751                                          TreeMapEntry<K,V> fence) {
1752                super(last, fence);
1753            }
1754
1755            public Map.Entry<K,V> next() {
1756                return prevEntry();
1757            }
1758            public void remove() {
1759                removeDescending();
1760            }
1761        }
1762
1763        // Implement minimal Spliterator as KeySpliterator backup
1764        final class SubMapKeyIterator extends SubMapIterator<K>
1765            implements Spliterator<K> {
1766            SubMapKeyIterator(TreeMapEntry<K,V> first,
1767                              TreeMapEntry<K,V> fence) {
1768                super(first, fence);
1769            }
1770            public K next() {
1771                return nextEntry().key;
1772            }
1773            public void remove() {
1774                removeAscending();
1775            }
1776            public Spliterator<K> trySplit() {
1777                return null;
1778            }
1779            public void forEachRemaining(Consumer<? super K> action) {
1780                while (hasNext())
1781                    action.accept(next());
1782            }
1783            public boolean tryAdvance(Consumer<? super K> action) {
1784                if (hasNext()) {
1785                    action.accept(next());
1786                    return true;
1787                }
1788                return false;
1789            }
1790            public long estimateSize() {
1791                return Long.MAX_VALUE;
1792            }
1793            public int characteristics() {
1794                return Spliterator.DISTINCT | Spliterator.ORDERED |
1795                    Spliterator.SORTED;
1796            }
1797            public final Comparator<? super K>  getComparator() {
1798                return NavigableSubMap.this.comparator();
1799            }
1800        }
1801
1802        final class DescendingSubMapKeyIterator extends SubMapIterator<K>
1803            implements Spliterator<K> {
1804            DescendingSubMapKeyIterator(TreeMapEntry<K,V> last,
1805                                        TreeMapEntry<K,V> fence) {
1806                super(last, fence);
1807            }
1808            public K next() {
1809                return prevEntry().key;
1810            }
1811            public void remove() {
1812                removeDescending();
1813            }
1814            public Spliterator<K> trySplit() {
1815                return null;
1816            }
1817            public void forEachRemaining(Consumer<? super K> action) {
1818                while (hasNext())
1819                    action.accept(next());
1820            }
1821            public boolean tryAdvance(Consumer<? super K> action) {
1822                if (hasNext()) {
1823                    action.accept(next());
1824                    return true;
1825                }
1826                return false;
1827            }
1828            public long estimateSize() {
1829                return Long.MAX_VALUE;
1830            }
1831            public int characteristics() {
1832                return Spliterator.DISTINCT | Spliterator.ORDERED;
1833            }
1834        }
1835    }
1836
1837    /**
1838     * @serial include
1839     */
1840    static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1841        private static final long serialVersionUID = 912986545866124060L;
1842
1843        AscendingSubMap(TreeMap<K,V> m,
1844                        boolean fromStart, K lo, boolean loInclusive,
1845                        boolean toEnd,     K hi, boolean hiInclusive) {
1846            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1847        }
1848
1849        public Comparator<? super K> comparator() {
1850            return m.comparator();
1851        }
1852
1853        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1854                                        K toKey,   boolean toInclusive) {
1855            if (!inRange(fromKey, fromInclusive))
1856                throw new IllegalArgumentException("fromKey out of range");
1857            if (!inRange(toKey, toInclusive))
1858                throw new IllegalArgumentException("toKey out of range");
1859            return new AscendingSubMap<>(m,
1860                                         false, fromKey, fromInclusive,
1861                                         false, toKey,   toInclusive);
1862        }
1863
1864        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1865            /* ----- BEGIN android -----
1866               Fix for edge cases
1867               if (!inRange(toKey, inclusive)) */
1868            if (!inRange(toKey) && !(!toEnd && m.compare(toKey, hi) == 0 &&
1869                !hiInclusive && !inclusive))
1870            // ----- END android -----
1871                throw new IllegalArgumentException("toKey out of range");
1872            return new AscendingSubMap<>(m,
1873                                         fromStart, lo,    loInclusive,
1874                                         false,     toKey, inclusive);
1875        }
1876
1877        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
1878            /* ----- BEGIN android -----
1879               Fix for edge cases
1880               if (!inRange(fromKey, inclusive)) */
1881            if (!inRange(fromKey) && !(!fromStart && m.compare(fromKey, lo) == 0 &&
1882                !loInclusive && !inclusive))
1883            // ----- END android -----
1884                throw new IllegalArgumentException("fromKey out of range");
1885            return new AscendingSubMap<>(m,
1886                                         false, fromKey, inclusive,
1887                                         toEnd, hi,      hiInclusive);
1888        }
1889
1890        public NavigableMap<K,V> descendingMap() {
1891            NavigableMap<K,V> mv = descendingMapView;
1892            return (mv != null) ? mv :
1893                (descendingMapView =
1894                 new DescendingSubMap<>(m,
1895                                        fromStart, lo, loInclusive,
1896                                        toEnd,     hi, hiInclusive));
1897        }
1898
1899        Iterator<K> keyIterator() {
1900            return new SubMapKeyIterator(absLowest(), absHighFence());
1901        }
1902
1903        Spliterator<K> keySpliterator() {
1904            return new SubMapKeyIterator(absLowest(), absHighFence());
1905        }
1906
1907        Iterator<K> descendingKeyIterator() {
1908            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1909        }
1910
1911        final class AscendingEntrySetView extends EntrySetView {
1912            public Iterator<Map.Entry<K,V>> iterator() {
1913                return new SubMapEntryIterator(absLowest(), absHighFence());
1914            }
1915        }
1916
1917        public Set<Map.Entry<K,V>> entrySet() {
1918            EntrySetView es = entrySetView;
1919            return (es != null) ? es : new AscendingEntrySetView();
1920        }
1921
1922        TreeMapEntry<K,V> subLowest()       { return absLowest(); }
1923        TreeMapEntry<K,V> subHighest()      { return absHighest(); }
1924        TreeMapEntry<K,V> subCeiling(K key) { return absCeiling(key); }
1925        TreeMapEntry<K,V> subHigher(K key)  { return absHigher(key); }
1926        TreeMapEntry<K,V> subFloor(K key)   { return absFloor(key); }
1927        TreeMapEntry<K,V> subLower(K key)   { return absLower(key); }
1928    }
1929
1930    /**
1931     * @serial include
1932     */
1933    static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1934        private static final long serialVersionUID = 912986545866120460L;
1935        DescendingSubMap(TreeMap<K,V> m,
1936                        boolean fromStart, K lo, boolean loInclusive,
1937                        boolean toEnd,     K hi, boolean hiInclusive) {
1938            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1939        }
1940
1941        private final Comparator<? super K> reverseComparator =
1942            Collections.reverseOrder(m.comparator);
1943
1944        public Comparator<? super K> comparator() {
1945            return reverseComparator;
1946        }
1947
1948        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1949                                        K toKey,   boolean toInclusive) {
1950            if (!inRange(fromKey, fromInclusive))
1951                throw new IllegalArgumentException("fromKey out of range");
1952            if (!inRange(toKey, toInclusive))
1953                throw new IllegalArgumentException("toKey out of range");
1954            return new DescendingSubMap<>(m,
1955                                          false, toKey,   toInclusive,
1956                                          false, fromKey, fromInclusive);
1957        }
1958
1959        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1960            /* ----- BEGIN android -----
1961               Fix for edge cases
1962               if (!inRange(toKey, inclusive)) */
1963            if (!inRange(toKey) && !(!fromStart && m.compare(toKey, lo) == 0 &&
1964                !loInclusive && !inclusive))
1965            // ----- END android -----
1966                throw new IllegalArgumentException("toKey out of range");
1967            return new DescendingSubMap<>(m,
1968                                          false, toKey, inclusive,
1969                                          toEnd, hi,    hiInclusive);
1970        }
1971
1972        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
1973            /* ----- BEGIN android -----
1974               Fix for edge cases
1975               if (!inRange(fromKey, inclusive)) */
1976            if (!inRange(fromKey) && !(!toEnd && m.compare(fromKey, hi) == 0 &&
1977                !hiInclusive && !inclusive))
1978            // ----- END android -----
1979                throw new IllegalArgumentException("fromKey out of range");
1980            return new DescendingSubMap<>(m,
1981                                          fromStart, lo, loInclusive,
1982                                          false, fromKey, inclusive);
1983        }
1984
1985        public NavigableMap<K,V> descendingMap() {
1986            NavigableMap<K,V> mv = descendingMapView;
1987            return (mv != null) ? mv :
1988                (descendingMapView =
1989                 new AscendingSubMap<>(m,
1990                                       fromStart, lo, loInclusive,
1991                                       toEnd,     hi, hiInclusive));
1992        }
1993
1994        Iterator<K> keyIterator() {
1995            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1996        }
1997
1998        Spliterator<K> keySpliterator() {
1999            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
2000        }
2001
2002        Iterator<K> descendingKeyIterator() {
2003            return new SubMapKeyIterator(absLowest(), absHighFence());
2004        }
2005
2006        final class DescendingEntrySetView extends EntrySetView {
2007            public Iterator<Map.Entry<K,V>> iterator() {
2008                return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
2009            }
2010        }
2011
2012        public Set<Map.Entry<K,V>> entrySet() {
2013            EntrySetView es = entrySetView;
2014            return (es != null) ? es : (entrySetView = new DescendingEntrySetView());
2015        }
2016
2017        TreeMapEntry<K,V> subLowest()       { return absHighest(); }
2018        TreeMapEntry<K,V> subHighest()      { return absLowest(); }
2019        TreeMapEntry<K,V> subCeiling(K key) { return absFloor(key); }
2020        TreeMapEntry<K,V> subHigher(K key)  { return absLower(key); }
2021        TreeMapEntry<K,V> subFloor(K key)   { return absCeiling(key); }
2022        TreeMapEntry<K,V> subLower(K key)   { return absHigher(key); }
2023    }
2024
2025    /**
2026     * This class exists solely for the sake of serialization
2027     * compatibility with previous releases of TreeMap that did not
2028     * support NavigableMap.  It translates an old-version SubMap into
2029     * a new-version AscendingSubMap. This class is never otherwise
2030     * used.
2031     *
2032     * @serial include
2033     */
2034    private class SubMap extends AbstractMap<K,V>
2035        implements SortedMap<K,V>, java.io.Serializable {
2036        private static final long serialVersionUID = -6520786458950516097L;
2037        private boolean fromStart = false, toEnd = false;
2038        private K fromKey, toKey;
2039        private Object readResolve() {
2040            return new AscendingSubMap<>(TreeMap.this,
2041                                         fromStart, fromKey, true,
2042                                         toEnd, toKey, false);
2043        }
2044        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
2045        public K lastKey() { throw new InternalError(); }
2046        public K firstKey() { throw new InternalError(); }
2047        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
2048        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
2049        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
2050        public Comparator<? super K> comparator() { throw new InternalError(); }
2051    }
2052
2053
2054    // Red-black mechanics
2055
2056    private static final boolean RED   = false;
2057    private static final boolean BLACK = true;
2058
2059    /**
2060     * Node in the Tree.  Doubles as a means to pass key-value pairs back to
2061     * user (see Map.Entry).
2062     */
2063
2064    static final class TreeMapEntry<K,V> implements Map.Entry<K,V> {
2065        K key;
2066        V value;
2067        TreeMapEntry<K,V> left = null;
2068        TreeMapEntry<K,V> right = null;
2069        TreeMapEntry<K,V> parent;
2070        boolean color = BLACK;
2071
2072        /**
2073         * Make a new cell with given key, value, and parent, and with
2074         * {@code null} child links, and BLACK color.
2075         */
2076        TreeMapEntry(K key, V value, TreeMapEntry<K,V> parent) {
2077            this.key = key;
2078            this.value = value;
2079            this.parent = parent;
2080        }
2081
2082        /**
2083         * Returns the key.
2084         *
2085         * @return the key
2086         */
2087        public K getKey() {
2088            return key;
2089        }
2090
2091        /**
2092         * Returns the value associated with the key.
2093         *
2094         * @return the value associated with the key
2095         */
2096        public V getValue() {
2097            return value;
2098        }
2099
2100        /**
2101         * Replaces the value currently associated with the key with the given
2102         * value.
2103         *
2104         * @return the value associated with the key before this method was
2105         *         called
2106         */
2107        public V setValue(V value) {
2108            V oldValue = this.value;
2109            this.value = value;
2110            return oldValue;
2111        }
2112
2113        public boolean equals(Object o) {
2114            if (!(o instanceof Map.Entry))
2115                return false;
2116            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2117
2118            return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
2119        }
2120
2121        public int hashCode() {
2122            int keyHash = (key==null ? 0 : key.hashCode());
2123            int valueHash = (value==null ? 0 : value.hashCode());
2124            return keyHash ^ valueHash;
2125        }
2126
2127        public String toString() {
2128            return key + "=" + value;
2129        }
2130    }
2131
2132    /**
2133     * Returns the first Entry in the TreeMap (according to the TreeMap's
2134     * key-sort function).  Returns null if the TreeMap is empty.
2135     */
2136    final TreeMapEntry<K,V> getFirstEntry() {
2137        TreeMapEntry<K,V> p = root;
2138        if (p != null)
2139            while (p.left != null)
2140                p = p.left;
2141        return p;
2142    }
2143
2144    /**
2145     * Returns the last Entry in the TreeMap (according to the TreeMap's
2146     * key-sort function).  Returns null if the TreeMap is empty.
2147     */
2148    final TreeMapEntry<K,V> getLastEntry() {
2149        TreeMapEntry<K,V> p = root;
2150        if (p != null)
2151            while (p.right != null)
2152                p = p.right;
2153        return p;
2154    }
2155
2156    /**
2157     * Returns the successor of the specified Entry, or null if no such.
2158     */
2159    static <K,V> TreeMapEntry<K,V> successor(TreeMapEntry<K,V> t) {
2160        if (t == null)
2161            return null;
2162        else if (t.right != null) {
2163            TreeMapEntry<K,V> p = t.right;
2164            while (p.left != null)
2165                p = p.left;
2166            return p;
2167        } else {
2168            TreeMapEntry<K,V> p = t.parent;
2169            TreeMapEntry<K,V> ch = t;
2170            while (p != null && ch == p.right) {
2171                ch = p;
2172                p = p.parent;
2173            }
2174            return p;
2175        }
2176    }
2177
2178    /**
2179     * Returns the predecessor of the specified Entry, or null if no such.
2180     */
2181    static <K,V> TreeMapEntry<K,V> predecessor(TreeMapEntry<K,V> t) {
2182        if (t == null)
2183            return null;
2184        else if (t.left != null) {
2185            TreeMapEntry<K,V> p = t.left;
2186            while (p.right != null)
2187                p = p.right;
2188            return p;
2189        } else {
2190            TreeMapEntry<K,V> p = t.parent;
2191            TreeMapEntry<K,V> ch = t;
2192            while (p != null && ch == p.left) {
2193                ch = p;
2194                p = p.parent;
2195            }
2196            return p;
2197        }
2198    }
2199
2200    /**
2201     * Balancing operations.
2202     *
2203     * Implementations of rebalancings during insertion and deletion are
2204     * slightly different than the CLR version.  Rather than using dummy
2205     * nilnodes, we use a set of accessors that deal properly with null.  They
2206     * are used to avoid messiness surrounding nullness checks in the main
2207     * algorithms.
2208     */
2209
2210    private static <K,V> boolean colorOf(TreeMapEntry<K,V> p) {
2211        return (p == null ? BLACK : p.color);
2212    }
2213
2214    private static <K,V> TreeMapEntry<K,V> parentOf(TreeMapEntry<K,V> p) {
2215        return (p == null ? null: p.parent);
2216    }
2217
2218    private static <K,V> void setColor(TreeMapEntry<K,V> p, boolean c) {
2219        if (p != null)
2220            p.color = c;
2221    }
2222
2223    private static <K,V> TreeMapEntry<K,V> leftOf(TreeMapEntry<K,V> p) {
2224        return (p == null) ? null: p.left;
2225    }
2226
2227    private static <K,V> TreeMapEntry<K,V> rightOf(TreeMapEntry<K,V> p) {
2228        return (p == null) ? null: p.right;
2229    }
2230
2231    /** From CLR */
2232    private void rotateLeft(TreeMapEntry<K,V> p) {
2233        if (p != null) {
2234            TreeMapEntry<K,V> r = p.right;
2235            p.right = r.left;
2236            if (r.left != null)
2237                r.left.parent = p;
2238            r.parent = p.parent;
2239            if (p.parent == null)
2240                root = r;
2241            else if (p.parent.left == p)
2242                p.parent.left = r;
2243            else
2244                p.parent.right = r;
2245            r.left = p;
2246            p.parent = r;
2247        }
2248    }
2249
2250    /** From CLR */
2251    private void rotateRight(TreeMapEntry<K,V> p) {
2252        if (p != null) {
2253            TreeMapEntry<K,V> l = p.left;
2254            p.left = l.right;
2255            if (l.right != null) l.right.parent = p;
2256            l.parent = p.parent;
2257            if (p.parent == null)
2258                root = l;
2259            else if (p.parent.right == p)
2260                p.parent.right = l;
2261            else p.parent.left = l;
2262            l.right = p;
2263            p.parent = l;
2264        }
2265    }
2266
2267    /** From CLR */
2268    private void fixAfterInsertion(TreeMapEntry<K,V> x) {
2269        x.color = RED;
2270
2271        while (x != null && x != root && x.parent.color == RED) {
2272            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
2273                TreeMapEntry<K,V> y = rightOf(parentOf(parentOf(x)));
2274                if (colorOf(y) == RED) {
2275                    setColor(parentOf(x), BLACK);
2276                    setColor(y, BLACK);
2277                    setColor(parentOf(parentOf(x)), RED);
2278                    x = parentOf(parentOf(x));
2279                } else {
2280                    if (x == rightOf(parentOf(x))) {
2281                        x = parentOf(x);
2282                        rotateLeft(x);
2283                    }
2284                    setColor(parentOf(x), BLACK);
2285                    setColor(parentOf(parentOf(x)), RED);
2286                    rotateRight(parentOf(parentOf(x)));
2287                }
2288            } else {
2289                TreeMapEntry<K,V> y = leftOf(parentOf(parentOf(x)));
2290                if (colorOf(y) == RED) {
2291                    setColor(parentOf(x), BLACK);
2292                    setColor(y, BLACK);
2293                    setColor(parentOf(parentOf(x)), RED);
2294                    x = parentOf(parentOf(x));
2295                } else {
2296                    if (x == leftOf(parentOf(x))) {
2297                        x = parentOf(x);
2298                        rotateRight(x);
2299                    }
2300                    setColor(parentOf(x), BLACK);
2301                    setColor(parentOf(parentOf(x)), RED);
2302                    rotateLeft(parentOf(parentOf(x)));
2303                }
2304            }
2305        }
2306        root.color = BLACK;
2307    }
2308
2309    /**
2310     * Delete node p, and then rebalance the tree.
2311     */
2312    private void deleteEntry(TreeMapEntry<K,V> p) {
2313        modCount++;
2314        size--;
2315
2316        // If strictly internal, copy successor's element to p and then make p
2317        // point to successor.
2318        if (p.left != null && p.right != null) {
2319            TreeMapEntry<K,V> s = successor(p);
2320            p.key = s.key;
2321            p.value = s.value;
2322            p = s;
2323        } // p has 2 children
2324
2325        // Start fixup at replacement node, if it exists.
2326        TreeMapEntry<K,V> replacement = (p.left != null ? p.left : p.right);
2327
2328        if (replacement != null) {
2329            // Link replacement to parent
2330            replacement.parent = p.parent;
2331            if (p.parent == null)
2332                root = replacement;
2333            else if (p == p.parent.left)
2334                p.parent.left  = replacement;
2335            else
2336                p.parent.right = replacement;
2337
2338            // Null out links so they are OK to use by fixAfterDeletion.
2339            p.left = p.right = p.parent = null;
2340
2341            // Fix replacement
2342            if (p.color == BLACK)
2343                fixAfterDeletion(replacement);
2344        } else if (p.parent == null) { // return if we are the only node.
2345            root = null;
2346        } else { //  No children. Use self as phantom replacement and unlink.
2347            if (p.color == BLACK)
2348                fixAfterDeletion(p);
2349
2350            if (p.parent != null) {
2351                if (p == p.parent.left)
2352                    p.parent.left = null;
2353                else if (p == p.parent.right)
2354                    p.parent.right = null;
2355                p.parent = null;
2356            }
2357        }
2358    }
2359
2360    /** From CLR */
2361    private void fixAfterDeletion(TreeMapEntry<K,V> x) {
2362        while (x != root && colorOf(x) == BLACK) {
2363            if (x == leftOf(parentOf(x))) {
2364                TreeMapEntry<K,V> sib = rightOf(parentOf(x));
2365
2366                if (colorOf(sib) == RED) {
2367                    setColor(sib, BLACK);
2368                    setColor(parentOf(x), RED);
2369                    rotateLeft(parentOf(x));
2370                    sib = rightOf(parentOf(x));
2371                }
2372
2373                if (colorOf(leftOf(sib))  == BLACK &&
2374                    colorOf(rightOf(sib)) == BLACK) {
2375                    setColor(sib, RED);
2376                    x = parentOf(x);
2377                } else {
2378                    if (colorOf(rightOf(sib)) == BLACK) {
2379                        setColor(leftOf(sib), BLACK);
2380                        setColor(sib, RED);
2381                        rotateRight(sib);
2382                        sib = rightOf(parentOf(x));
2383                    }
2384                    setColor(sib, colorOf(parentOf(x)));
2385                    setColor(parentOf(x), BLACK);
2386                    setColor(rightOf(sib), BLACK);
2387                    rotateLeft(parentOf(x));
2388                    x = root;
2389                }
2390            } else { // symmetric
2391                TreeMapEntry<K,V> sib = leftOf(parentOf(x));
2392
2393                if (colorOf(sib) == RED) {
2394                    setColor(sib, BLACK);
2395                    setColor(parentOf(x), RED);
2396                    rotateRight(parentOf(x));
2397                    sib = leftOf(parentOf(x));
2398                }
2399
2400                if (colorOf(rightOf(sib)) == BLACK &&
2401                    colorOf(leftOf(sib)) == BLACK) {
2402                    setColor(sib, RED);
2403                    x = parentOf(x);
2404                } else {
2405                    if (colorOf(leftOf(sib)) == BLACK) {
2406                        setColor(rightOf(sib), BLACK);
2407                        setColor(sib, RED);
2408                        rotateLeft(sib);
2409                        sib = leftOf(parentOf(x));
2410                    }
2411                    setColor(sib, colorOf(parentOf(x)));
2412                    setColor(parentOf(x), BLACK);
2413                    setColor(leftOf(sib), BLACK);
2414                    rotateRight(parentOf(x));
2415                    x = root;
2416                }
2417            }
2418        }
2419
2420        setColor(x, BLACK);
2421    }
2422
2423    private static final long serialVersionUID = 919286545866124006L;
2424
2425    /**
2426     * Save the state of the {@code TreeMap} instance to a stream (i.e.,
2427     * serialize it).
2428     *
2429     * @serialData The <em>size</em> of the TreeMap (the number of key-value
2430     *             mappings) is emitted (int), followed by the key (Object)
2431     *             and value (Object) for each key-value mapping represented
2432     *             by the TreeMap. The key-value mappings are emitted in
2433     *             key-order (as determined by the TreeMap's Comparator,
2434     *             or by the keys' natural ordering if the TreeMap has no
2435     *             Comparator).
2436     */
2437    private void writeObject(java.io.ObjectOutputStream s)
2438        throws java.io.IOException {
2439        // Write out the Comparator and any hidden stuff
2440        s.defaultWriteObject();
2441
2442        // Write out size (number of Mappings)
2443        s.writeInt(size);
2444
2445        // Write out keys and values (alternating)
2446        for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
2447            Map.Entry<K,V> e = i.next();
2448            s.writeObject(e.getKey());
2449            s.writeObject(e.getValue());
2450        }
2451    }
2452
2453    /**
2454     * Reconstitute the {@code TreeMap} instance from a stream (i.e.,
2455     * deserialize it).
2456     */
2457    private void readObject(final java.io.ObjectInputStream s)
2458        throws java.io.IOException, ClassNotFoundException {
2459        // Read in the Comparator and any hidden stuff
2460        s.defaultReadObject();
2461
2462        // Read in size
2463        int size = s.readInt();
2464
2465        buildFromSorted(size, null, s, null);
2466    }
2467
2468    /** Intended to be called only from TreeSet.readObject */
2469    void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2470        throws java.io.IOException, ClassNotFoundException {
2471        buildFromSorted(size, null, s, defaultVal);
2472    }
2473
2474    /** Intended to be called only from TreeSet.addAll */
2475    void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2476        try {
2477            buildFromSorted(set.size(), set.iterator(), null, defaultVal);
2478        } catch (java.io.IOException cannotHappen) {
2479        } catch (ClassNotFoundException cannotHappen) {
2480        }
2481    }
2482
2483
2484    /**
2485     * Linear time tree building algorithm from sorted data.  Can accept keys
2486     * and/or values from iterator or stream. This leads to too many
2487     * parameters, but seems better than alternatives.  The four formats
2488     * that this method accepts are:
2489     *
2490     *    1) An iterator of Map.Entries.  (it != null, defaultVal == null).
2491     *    2) An iterator of keys.         (it != null, defaultVal != null).
2492     *    3) A stream of alternating serialized keys and values.
2493     *                                   (it == null, defaultVal == null).
2494     *    4) A stream of serialized keys. (it == null, defaultVal != null).
2495     *
2496     * It is assumed that the comparator of the TreeMap is already set prior
2497     * to calling this method.
2498     *
2499     * @param size the number of keys (or key-value pairs) to be read from
2500     *        the iterator or stream
2501     * @param it If non-null, new entries are created from entries
2502     *        or keys read from this iterator.
2503     * @param str If non-null, new entries are created from keys and
2504     *        possibly values read from this stream in serialized form.
2505     *        Exactly one of it and str should be non-null.
2506     * @param defaultVal if non-null, this default value is used for
2507     *        each value in the map.  If null, each value is read from
2508     *        iterator or stream, as described above.
2509     * @throws java.io.IOException propagated from stream reads. This cannot
2510     *         occur if str is null.
2511     * @throws ClassNotFoundException propagated from readObject.
2512     *         This cannot occur if str is null.
2513     */
2514    private void buildFromSorted(int size, Iterator<?> it,
2515                                 java.io.ObjectInputStream str,
2516                                 V defaultVal)
2517        throws  java.io.IOException, ClassNotFoundException {
2518        this.size = size;
2519        root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2520                               it, str, defaultVal);
2521    }
2522
2523    /**
2524     * Recursive "helper method" that does the real work of the
2525     * previous method.  Identically named parameters have
2526     * identical definitions.  Additional parameters are documented below.
2527     * It is assumed that the comparator and size fields of the TreeMap are
2528     * already set prior to calling this method.  (It ignores both fields.)
2529     *
2530     * @param level the current level of tree. Initial call should be 0.
2531     * @param lo the first element index of this subtree. Initial should be 0.
2532     * @param hi the last element index of this subtree.  Initial should be
2533     *        size-1.
2534     * @param redLevel the level at which nodes should be red.
2535     *        Must be equal to computeRedLevel for tree of this size.
2536     */
2537    @SuppressWarnings("unchecked")
2538    private final TreeMapEntry<K,V> buildFromSorted(int level, int lo, int hi,
2539                                             int redLevel,
2540                                             Iterator<?> it,
2541                                             java.io.ObjectInputStream str,
2542                                             V defaultVal)
2543        throws  java.io.IOException, ClassNotFoundException {
2544        /*
2545         * Strategy: The root is the middlemost element. To get to it, we
2546         * have to first recursively construct the entire left subtree,
2547         * so as to grab all of its elements. We can then proceed with right
2548         * subtree.
2549         *
2550         * The lo and hi arguments are the minimum and maximum
2551         * indices to pull out of the iterator or stream for current subtree.
2552         * They are not actually indexed, we just proceed sequentially,
2553         * ensuring that items are extracted in corresponding order.
2554         */
2555
2556        if (hi < lo) return null;
2557
2558        int mid = (lo + hi) >>> 1;
2559
2560        TreeMapEntry<K,V> left  = null;
2561        if (lo < mid)
2562            left = buildFromSorted(level+1, lo, mid - 1, redLevel,
2563                                   it, str, defaultVal);
2564
2565        // extract key and/or value from iterator or stream
2566        K key;
2567        V value;
2568        if (it != null) {
2569            if (defaultVal==null) {
2570                Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
2571                key = entry.getKey();
2572                value = entry.getValue();
2573            } else {
2574                key = (K)it.next();
2575                value = defaultVal;
2576            }
2577        } else { // use stream
2578            key = (K) str.readObject();
2579            value = (defaultVal != null ? defaultVal : (V) str.readObject());
2580        }
2581
2582        TreeMapEntry<K,V> middle =  new TreeMapEntry<>(key, value, null);
2583
2584        // color nodes in non-full bottommost level red
2585        if (level == redLevel)
2586            middle.color = RED;
2587
2588        if (left != null) {
2589            middle.left = left;
2590            left.parent = middle;
2591        }
2592
2593        if (mid < hi) {
2594            TreeMapEntry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
2595                                               it, str, defaultVal);
2596            middle.right = right;
2597            right.parent = middle;
2598        }
2599
2600        return middle;
2601    }
2602
2603    /**
2604     * Find the level down to which to assign all nodes BLACK.  This is the
2605     * last `full' level of the complete binary tree produced by
2606     * buildTree. The remaining nodes are colored RED. (This makes a `nice'
2607     * set of color assignments wrt future insertions.) This level number is
2608     * computed by finding the number of splits needed to reach the zeroeth
2609     * node.  (The answer is ~lg(N), but in any case must be computed by same
2610     * quick O(lg(N)) loop.)
2611     */
2612    private static int computeRedLevel(int sz) {
2613        int level = 0;
2614        for (int m = sz - 1; m >= 0; m = m / 2 - 1)
2615            level++;
2616        return level;
2617    }
2618
2619    /**
2620     * Currently, we support Spliterator-based versions only for the
2621     * full map, in either plain of descending form, otherwise relying
2622     * on defaults because size estimation for submaps would dominate
2623     * costs. The type tests needed to check these for key views are
2624     * not very nice but avoid disrupting existing class
2625     * structures. Callers must use plain default spliterators if this
2626     * returns null.
2627     */
2628    static <K> Spliterator<K> keySpliteratorFor(NavigableMap<K,?> m) {
2629        if (m instanceof TreeMap) {
2630            @SuppressWarnings("unchecked") TreeMap<K,Object> t =
2631                (TreeMap<K,Object>) m;
2632            return t.keySpliterator();
2633        }
2634        if (m instanceof DescendingSubMap) {
2635            @SuppressWarnings("unchecked") DescendingSubMap<K,?> dm =
2636                (DescendingSubMap<K,?>) m;
2637            TreeMap<K,?> tm = dm.m;
2638            if (dm == tm.descendingMap) {
2639                @SuppressWarnings("unchecked") TreeMap<K,Object> t =
2640                    (TreeMap<K,Object>) tm;
2641                return t.descendingKeySpliterator();
2642            }
2643        }
2644        @SuppressWarnings("unchecked") NavigableSubMap<K,?> sm =
2645            (NavigableSubMap<K,?>) m;
2646        return sm.keySpliterator();
2647    }
2648
2649    final Spliterator<K> keySpliterator() {
2650        return new KeySpliterator<K,V>(this, null, null, 0, -1, 0);
2651    }
2652
2653    final Spliterator<K> descendingKeySpliterator() {
2654        return new DescendingKeySpliterator<K,V>(this, null, null, 0, -2, 0);
2655    }
2656
2657    /**
2658     * Base class for spliterators.  Iteration starts at a given
2659     * origin and continues up to but not including a given fence (or
2660     * null for end).  At top-level, for ascending cases, the first
2661     * split uses the root as left-fence/right-origin. From there,
2662     * right-hand splits replace the current fence with its left
2663     * child, also serving as origin for the split-off spliterator.
2664     * Left-hands are symmetric. Descending versions place the origin
2665     * at the end and invert ascending split rules.  This base class
2666     * is non-commital about directionality, or whether the top-level
2667     * spliterator covers the whole tree. This means that the actual
2668     * split mechanics are located in subclasses. Some of the subclass
2669     * trySplit methods are identical (except for return types), but
2670     * not nicely factorable.
2671     *
2672     * Currently, subclass versions exist only for the full map
2673     * (including descending keys via its descendingMap).  Others are
2674     * possible but currently not worthwhile because submaps require
2675     * O(n) computations to determine size, which substantially limits
2676     * potential speed-ups of using custom Spliterators versus default
2677     * mechanics.
2678     *
2679     * To boostrap initialization, external constructors use
2680     * negative size estimates: -1 for ascend, -2 for descend.
2681     */
2682    static class TreeMapSpliterator<K,V> {
2683        final TreeMap<K,V> tree;
2684        TreeMapEntry<K,V> current; // traverser; initially first node in range
2685        TreeMapEntry<K,V> fence;   // one past last, or null
2686        int side;                   // 0: top, -1: is a left split, +1: right
2687        int est;                    // size estimate (exact only for top-level)
2688        int expectedModCount;       // for CME checks
2689
2690        TreeMapSpliterator(TreeMap<K,V> tree,
2691                           TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2692                           int side, int est, int expectedModCount) {
2693            this.tree = tree;
2694            this.current = origin;
2695            this.fence = fence;
2696            this.side = side;
2697            this.est = est;
2698            this.expectedModCount = expectedModCount;
2699        }
2700
2701        final int getEstimate() { // force initialization
2702            int s; TreeMap<K,V> t;
2703            if ((s = est) < 0) {
2704                if ((t = tree) != null) {
2705                    current = (s == -1) ? t.getFirstEntry() : t.getLastEntry();
2706                    s = est = t.size;
2707                    expectedModCount = t.modCount;
2708                }
2709                else
2710                    s = est = 0;
2711            }
2712            return s;
2713        }
2714
2715        public final long estimateSize() {
2716            return (long)getEstimate();
2717        }
2718    }
2719
2720    static final class KeySpliterator<K,V>
2721        extends TreeMapSpliterator<K,V>
2722        implements Spliterator<K> {
2723        KeySpliterator(TreeMap<K,V> tree,
2724                       TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2725                       int side, int est, int expectedModCount) {
2726            super(tree, origin, fence, side, est, expectedModCount);
2727        }
2728
2729        public KeySpliterator<K,V> trySplit() {
2730            if (est < 0)
2731                getEstimate(); // force initialization
2732            int d = side;
2733            TreeMapEntry<K,V> e = current, f = fence,
2734                s = ((e == null || e == f) ? null :      // empty
2735                     (d == 0)              ? tree.root : // was top
2736                     (d >  0)              ? e.right :   // was right
2737                     (d <  0 && f != null) ? f.left :    // was left
2738                     null);
2739            if (s != null && s != e && s != f &&
2740                tree.compare(e.key, s.key) < 0) {        // e not already past s
2741                side = 1;
2742                return new KeySpliterator<>
2743                    (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2744            }
2745            return null;
2746        }
2747
2748        public void forEachRemaining(Consumer<? super K> action) {
2749            if (action == null)
2750                throw new NullPointerException();
2751            if (est < 0)
2752                getEstimate(); // force initialization
2753            TreeMapEntry<K,V> f = fence, e, p, pl;
2754            if ((e = current) != null && e != f) {
2755                current = f; // exhaust
2756                do {
2757                    action.accept(e.key);
2758                    if ((p = e.right) != null) {
2759                        while ((pl = p.left) != null)
2760                            p = pl;
2761                    }
2762                    else {
2763                        while ((p = e.parent) != null && e == p.right)
2764                            e = p;
2765                    }
2766                } while ((e = p) != null && e != f);
2767                if (tree.modCount != expectedModCount)
2768                    throw new ConcurrentModificationException();
2769            }
2770        }
2771
2772        public boolean tryAdvance(Consumer<? super K> action) {
2773            TreeMapEntry<K,V> e;
2774            if (action == null)
2775                throw new NullPointerException();
2776            if (est < 0)
2777                getEstimate(); // force initialization
2778            if ((e = current) == null || e == fence)
2779                return false;
2780            current = successor(e);
2781            action.accept(e.key);
2782            if (tree.modCount != expectedModCount)
2783                throw new ConcurrentModificationException();
2784            return true;
2785        }
2786
2787        public int characteristics() {
2788            return (side == 0 ? Spliterator.SIZED : 0) |
2789                Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
2790        }
2791
2792        public final Comparator<? super K>  getComparator() {
2793            return tree.comparator;
2794        }
2795
2796    }
2797
2798    static final class DescendingKeySpliterator<K,V>
2799        extends TreeMapSpliterator<K,V>
2800        implements Spliterator<K> {
2801        DescendingKeySpliterator(TreeMap<K,V> tree,
2802                                 TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2803                                 int side, int est, int expectedModCount) {
2804            super(tree, origin, fence, side, est, expectedModCount);
2805        }
2806
2807        public DescendingKeySpliterator<K,V> trySplit() {
2808            if (est < 0)
2809                getEstimate(); // force initialization
2810            int d = side;
2811            TreeMapEntry<K,V> e = current, f = fence,
2812                    s = ((e == null || e == f) ? null :      // empty
2813                         (d == 0)              ? tree.root : // was top
2814                         (d <  0)              ? e.left :    // was left
2815                         (d >  0 && f != null) ? f.right :   // was right
2816                         null);
2817            if (s != null && s != e && s != f &&
2818                tree.compare(e.key, s.key) > 0) {       // e not already past s
2819                side = 1;
2820                return new DescendingKeySpliterator<>
2821                        (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2822            }
2823            return null;
2824        }
2825
2826        public void forEachRemaining(Consumer<? super K> action) {
2827            if (action == null)
2828                throw new NullPointerException();
2829            if (est < 0)
2830                getEstimate(); // force initialization
2831            TreeMapEntry<K,V> f = fence, e, p, pr;
2832            if ((e = current) != null && e != f) {
2833                current = f; // exhaust
2834                do {
2835                    action.accept(e.key);
2836                    if ((p = e.left) != null) {
2837                        while ((pr = p.right) != null)
2838                            p = pr;
2839                    }
2840                    else {
2841                        while ((p = e.parent) != null && e == p.left)
2842                            e = p;
2843                    }
2844                } while ((e = p) != null && e != f);
2845                if (tree.modCount != expectedModCount)
2846                    throw new ConcurrentModificationException();
2847            }
2848        }
2849
2850        public boolean tryAdvance(Consumer<? super K> action) {
2851            TreeMapEntry<K,V> e;
2852            if (action == null)
2853                throw new NullPointerException();
2854            if (est < 0)
2855                getEstimate(); // force initialization
2856            if ((e = current) == null || e == fence)
2857                return false;
2858            current = predecessor(e);
2859            action.accept(e.key);
2860            if (tree.modCount != expectedModCount)
2861                throw new ConcurrentModificationException();
2862            return true;
2863        }
2864
2865        public int characteristics() {
2866            return (side == 0 ? Spliterator.SIZED : 0) |
2867                Spliterator.DISTINCT | Spliterator.ORDERED;
2868        }
2869    }
2870
2871    static final class ValueSpliterator<K,V>
2872            extends TreeMapSpliterator<K,V>
2873            implements Spliterator<V> {
2874        ValueSpliterator(TreeMap<K,V> tree,
2875                         TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2876                         int side, int est, int expectedModCount) {
2877            super(tree, origin, fence, side, est, expectedModCount);
2878        }
2879
2880        public ValueSpliterator<K,V> trySplit() {
2881            if (est < 0)
2882                getEstimate(); // force initialization
2883            int d = side;
2884            TreeMapEntry<K,V> e = current, f = fence,
2885                    s = ((e == null || e == f) ? null :      // empty
2886                         (d == 0)              ? tree.root : // was top
2887                         (d >  0)              ? e.right :   // was right
2888                         (d <  0 && f != null) ? f.left :    // was left
2889                         null);
2890            if (s != null && s != e && s != f &&
2891                tree.compare(e.key, s.key) < 0) {        // e not already past s
2892                side = 1;
2893                return new ValueSpliterator<>
2894                        (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2895            }
2896            return null;
2897        }
2898
2899        public void forEachRemaining(Consumer<? super V> action) {
2900            if (action == null)
2901                throw new NullPointerException();
2902            if (est < 0)
2903                getEstimate(); // force initialization
2904            TreeMapEntry<K,V> f = fence, e, p, pl;
2905            if ((e = current) != null && e != f) {
2906                current = f; // exhaust
2907                do {
2908                    action.accept(e.value);
2909                    if ((p = e.right) != null) {
2910                        while ((pl = p.left) != null)
2911                            p = pl;
2912                    }
2913                    else {
2914                        while ((p = e.parent) != null && e == p.right)
2915                            e = p;
2916                    }
2917                } while ((e = p) != null && e != f);
2918                if (tree.modCount != expectedModCount)
2919                    throw new ConcurrentModificationException();
2920            }
2921        }
2922
2923        public boolean tryAdvance(Consumer<? super V> action) {
2924            TreeMapEntry<K,V> e;
2925            if (action == null)
2926                throw new NullPointerException();
2927            if (est < 0)
2928                getEstimate(); // force initialization
2929            if ((e = current) == null || e == fence)
2930                return false;
2931            current = successor(e);
2932            action.accept(e.value);
2933            if (tree.modCount != expectedModCount)
2934                throw new ConcurrentModificationException();
2935            return true;
2936        }
2937
2938        public int characteristics() {
2939            return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.ORDERED;
2940        }
2941    }
2942
2943    static final class EntrySpliterator<K,V>
2944        extends TreeMapSpliterator<K,V>
2945        implements Spliterator<Map.Entry<K,V>> {
2946        EntrySpliterator(TreeMap<K,V> tree,
2947                         TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2948                         int side, int est, int expectedModCount) {
2949            super(tree, origin, fence, side, est, expectedModCount);
2950        }
2951
2952        public EntrySpliterator<K,V> trySplit() {
2953            if (est < 0)
2954                getEstimate(); // force initialization
2955            int d = side;
2956            TreeMapEntry<K,V> e = current, f = fence,
2957                    s = ((e == null || e == f) ? null :      // empty
2958                         (d == 0)              ? tree.root : // was top
2959                         (d >  0)              ? e.right :   // was right
2960                         (d <  0 && f != null) ? f.left :    // was left
2961                         null);
2962            if (s != null && s != e && s != f &&
2963                tree.compare(e.key, s.key) < 0) {        // e not already past s
2964                side = 1;
2965                return new EntrySpliterator<>
2966                        (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2967            }
2968            return null;
2969        }
2970
2971        public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
2972            if (action == null)
2973                throw new NullPointerException();
2974            if (est < 0)
2975                getEstimate(); // force initialization
2976            TreeMapEntry<K,V> f = fence, e, p, pl;
2977            if ((e = current) != null && e != f) {
2978                current = f; // exhaust
2979                do {
2980                    action.accept(e);
2981                    if ((p = e.right) != null) {
2982                        while ((pl = p.left) != null)
2983                            p = pl;
2984                    }
2985                    else {
2986                        while ((p = e.parent) != null && e == p.right)
2987                            e = p;
2988                    }
2989                } while ((e = p) != null && e != f);
2990                if (tree.modCount != expectedModCount)
2991                    throw new ConcurrentModificationException();
2992            }
2993        }
2994
2995        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
2996            TreeMapEntry<K,V> e;
2997            if (action == null)
2998                throw new NullPointerException();
2999            if (est < 0)
3000                getEstimate(); // force initialization
3001            if ((e = current) == null || e == fence)
3002                return false;
3003            current = successor(e);
3004            action.accept(e);
3005            if (tree.modCount != expectedModCount)
3006                throw new ConcurrentModificationException();
3007            return true;
3008        }
3009
3010        public int characteristics() {
3011            return (side == 0 ? Spliterator.SIZED : 0) |
3012                    Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
3013        }
3014
3015        @Override
3016        public Comparator<Map.Entry<K, V>> getComparator() {
3017            // Adapt or create a key-based comparator
3018            if (tree.comparator != null) {
3019                return Map.Entry.comparingByKey(tree.comparator);
3020            }
3021            else {
3022                return (Comparator<Map.Entry<K, V>> & Serializable) (e1, e2) -> {
3023                    @SuppressWarnings("unchecked")
3024                    Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey();
3025                    return k1.compareTo(e2.getKey());
3026                };
3027            }
3028        }
3029    }
3030}
3031