TreeMap.java revision 3733bc930b4f8a02b278dde1109d0cd42f7c4c08
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}openjdk-redirect.html?v=8&path=/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            compare(key, key); // type (and possibly null) check
540
541            root = new TreeMapEntry<>(key, value, null);
542            size = 1;
543            modCount++;
544            return null;
545        }
546        int cmp;
547        TreeMapEntry<K,V> parent;
548        // split comparator and comparable paths
549        Comparator<? super K> cpr = comparator;
550        if (cpr != null) {
551            do {
552                parent = t;
553                cmp = cpr.compare(key, t.key);
554                if (cmp < 0)
555                    t = t.left;
556                else if (cmp > 0)
557                    t = t.right;
558                else
559                    return t.setValue(value);
560            } while (t != null);
561        }
562        else {
563            if (key == null)
564                throw new NullPointerException();
565            @SuppressWarnings("unchecked")
566                Comparable<? super K> k = (Comparable<? super K>) key;
567            do {
568                parent = t;
569                cmp = k.compareTo(t.key);
570                if (cmp < 0)
571                    t = t.left;
572                else if (cmp > 0)
573                    t = t.right;
574                else
575                    return t.setValue(value);
576            } while (t != null);
577        }
578        TreeMapEntry<K,V> e = new TreeMapEntry<>(key, value, parent);
579        if (cmp < 0)
580            parent.left = e;
581        else
582            parent.right = e;
583        fixAfterInsertion(e);
584        size++;
585        modCount++;
586        return null;
587    }
588
589    /**
590     * Removes the mapping for this key from this TreeMap if present.
591     *
592     * @param  key key for which mapping should be removed
593     * @return the previous value associated with {@code key}, or
594     *         {@code null} if there was no mapping for {@code key}.
595     *         (A {@code null} return can also indicate that the map
596     *         previously associated {@code null} with {@code key}.)
597     * @throws ClassCastException if the specified key cannot be compared
598     *         with the keys currently in the map
599     * @throws NullPointerException if the specified key is null
600     *         and this map uses natural ordering, or its comparator
601     *         does not permit null keys
602     */
603    public V remove(Object key) {
604        TreeMapEntry<K,V> p = getEntry(key);
605        if (p == null)
606            return null;
607
608        V oldValue = p.value;
609        deleteEntry(p);
610        return oldValue;
611    }
612
613    /**
614     * Removes all of the mappings from this map.
615     * The map will be empty after this call returns.
616     */
617    public void clear() {
618        modCount++;
619        size = 0;
620        root = null;
621    }
622
623    /**
624     * Returns a shallow copy of this {@code TreeMap} instance. (The keys and
625     * values themselves are not cloned.)
626     *
627     * @return a shallow copy of this map
628     */
629    public Object clone() {
630        TreeMap<?,?> clone;
631        try {
632            clone = (TreeMap<?,?>) super.clone();
633        } catch (CloneNotSupportedException e) {
634            throw new InternalError(e);
635        }
636
637        // Put clone into "virgin" state (except for comparator)
638        clone.root = null;
639        clone.size = 0;
640        clone.modCount = 0;
641        clone.entrySet = null;
642        clone.navigableKeySet = null;
643        clone.descendingMap = null;
644
645        // Initialize clone with our mappings
646        try {
647            clone.buildFromSorted(size, entrySet().iterator(), null, null);
648        } catch (java.io.IOException cannotHappen) {
649        } catch (ClassNotFoundException cannotHappen) {
650        }
651
652        return clone;
653    }
654
655    // NavigableMap API methods
656
657    /**
658     * @since 1.6
659     */
660    public Map.Entry<K,V> firstEntry() {
661        return exportEntry(getFirstEntry());
662    }
663
664    /**
665     * @since 1.6
666     */
667    public Map.Entry<K,V> lastEntry() {
668        return exportEntry(getLastEntry());
669    }
670
671    /**
672     * @since 1.6
673     */
674    public Map.Entry<K,V> pollFirstEntry() {
675        TreeMapEntry<K,V> p = getFirstEntry();
676        Map.Entry<K,V> result = exportEntry(p);
677        if (p != null)
678            deleteEntry(p);
679        return result;
680    }
681
682    /**
683     * @since 1.6
684     */
685    public Map.Entry<K,V> pollLastEntry() {
686        TreeMapEntry<K,V> p = getLastEntry();
687        Map.Entry<K,V> result = exportEntry(p);
688        if (p != null)
689            deleteEntry(p);
690        return result;
691    }
692
693    /**
694     * @throws ClassCastException {@inheritDoc}
695     * @throws NullPointerException if the specified key is null
696     *         and this map uses natural ordering, or its comparator
697     *         does not permit null keys
698     * @since 1.6
699     */
700    public Map.Entry<K,V> lowerEntry(K key) {
701        return exportEntry(getLowerEntry(key));
702    }
703
704    /**
705     * @throws ClassCastException {@inheritDoc}
706     * @throws NullPointerException if the specified key is null
707     *         and this map uses natural ordering, or its comparator
708     *         does not permit null keys
709     * @since 1.6
710     */
711    public K lowerKey(K key) {
712        return keyOrNull(getLowerEntry(key));
713    }
714
715    /**
716     * @throws ClassCastException {@inheritDoc}
717     * @throws NullPointerException if the specified key is null
718     *         and this map uses natural ordering, or its comparator
719     *         does not permit null keys
720     * @since 1.6
721     */
722    public Map.Entry<K,V> floorEntry(K key) {
723        return exportEntry(getFloorEntry(key));
724    }
725
726    /**
727     * @throws ClassCastException {@inheritDoc}
728     * @throws NullPointerException if the specified key is null
729     *         and this map uses natural ordering, or its comparator
730     *         does not permit null keys
731     * @since 1.6
732     */
733    public K floorKey(K key) {
734        return keyOrNull(getFloorEntry(key));
735    }
736
737    /**
738     * @throws ClassCastException {@inheritDoc}
739     * @throws NullPointerException if the specified key is null
740     *         and this map uses natural ordering, or its comparator
741     *         does not permit null keys
742     * @since 1.6
743     */
744    public Map.Entry<K,V> ceilingEntry(K key) {
745        return exportEntry(getCeilingEntry(key));
746    }
747
748    /**
749     * @throws ClassCastException {@inheritDoc}
750     * @throws NullPointerException if the specified key is null
751     *         and this map uses natural ordering, or its comparator
752     *         does not permit null keys
753     * @since 1.6
754     */
755    public K ceilingKey(K key) {
756        return keyOrNull(getCeilingEntry(key));
757    }
758
759    /**
760     * @throws ClassCastException {@inheritDoc}
761     * @throws NullPointerException if the specified key is null
762     *         and this map uses natural ordering, or its comparator
763     *         does not permit null keys
764     * @since 1.6
765     */
766    public Map.Entry<K,V> higherEntry(K key) {
767        return exportEntry(getHigherEntry(key));
768    }
769
770    /**
771     * @throws ClassCastException {@inheritDoc}
772     * @throws NullPointerException if the specified key is null
773     *         and this map uses natural ordering, or its comparator
774     *         does not permit null keys
775     * @since 1.6
776     */
777    public K higherKey(K key) {
778        return keyOrNull(getHigherEntry(key));
779    }
780
781    // Views
782
783    /**
784     * Fields initialized to contain an instance of the entry set view
785     * the first time this view is requested.  Views are stateless, so
786     * there's no reason to create more than one.
787     */
788    private transient EntrySet entrySet = null;
789    private transient KeySet<K> navigableKeySet = null;
790    private transient NavigableMap<K,V> descendingMap = null;
791
792    /**
793     * Returns a {@link Set} view of the keys contained in this map.
794     *
795     * <p>The set's iterator returns the keys in ascending order.
796     * The set's spliterator is
797     * <em><a href="Spliterator.html#binding">late-binding</a></em>,
798     * <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED}
799     * and {@link Spliterator#ORDERED} with an encounter order that is ascending
800     * key order.  The spliterator's comparator (see
801     * {@link java.util.Spliterator#getComparator()}) is {@code null} if
802     * the tree map's comparator (see {@link #comparator()}) is {@code null}.
803     * Otherwise, the spliterator's comparator is the same as or imposes the
804     * same total ordering as the tree map's comparator.
805     *
806     * <p>The set is backed by the map, so changes to the map are
807     * reflected in the set, and vice-versa.  If the map is modified
808     * while an iteration over the set is in progress (except through
809     * the iterator's own {@code remove} operation), the results of
810     * the iteration are undefined.  The set supports element removal,
811     * which removes the corresponding mapping from the map, via the
812     * {@code Iterator.remove}, {@code Set.remove},
813     * {@code removeAll}, {@code retainAll}, and {@code clear}
814     * operations.  It does not support the {@code add} or {@code addAll}
815     * operations.
816     */
817    public Set<K> keySet() {
818        return navigableKeySet();
819    }
820
821    /**
822     * @since 1.6
823     */
824    public NavigableSet<K> navigableKeySet() {
825        KeySet<K> nks = navigableKeySet;
826        return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
827    }
828
829    /**
830     * @since 1.6
831     */
832    public NavigableSet<K> descendingKeySet() {
833        return descendingMap().navigableKeySet();
834    }
835
836    /**
837     * Returns a {@link Collection} view of the values contained in this map.
838     *
839     * <p>The collection's iterator returns the values in ascending order
840     * of the corresponding keys. The collection's spliterator is
841     * <em><a href="Spliterator.html#binding">late-binding</a></em>,
842     * <em>fail-fast</em>, and additionally reports {@link Spliterator#ORDERED}
843     * with an encounter order that is ascending order of the corresponding
844     * keys.
845     *
846     * <p>The collection is backed by the map, so changes to the map are
847     * reflected in the collection, and vice-versa.  If the map is
848     * modified while an iteration over the collection is in progress
849     * (except through the iterator's own {@code remove} operation),
850     * the results of the iteration are undefined.  The collection
851     * supports element removal, which removes the corresponding
852     * mapping from the map, via the {@code Iterator.remove},
853     * {@code Collection.remove}, {@code removeAll},
854     * {@code retainAll} and {@code clear} operations.  It does not
855     * support the {@code add} or {@code addAll} operations.
856     */
857    public Collection<V> values() {
858        Collection<V> vs = values;
859        return (vs != null) ? vs : (values = new Values());
860    }
861
862    /**
863     * Returns a {@link Set} view of the mappings contained in this map.
864     *
865     * <p>The set's iterator returns the entries in ascending key order. The
866     * sets's spliterator is
867     * <em><a href="Spliterator.html#binding">late-binding</a></em>,
868     * <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED} and
869     * {@link Spliterator#ORDERED} with an encounter order that is ascending key
870     * order.
871     *
872     * <p>The set is backed by the map, so changes to the map are
873     * reflected in the set, and vice-versa.  If the map is modified
874     * while an iteration over the set is in progress (except through
875     * the iterator's own {@code remove} operation, or through the
876     * {@code setValue} operation on a map entry returned by the
877     * iterator) the results of the iteration are undefined.  The set
878     * supports element removal, which removes the corresponding
879     * mapping from the map, via the {@code Iterator.remove},
880     * {@code Set.remove}, {@code removeAll}, {@code retainAll} and
881     * {@code clear} operations.  It does not support the
882     * {@code add} or {@code addAll} operations.
883     */
884    public Set<Map.Entry<K,V>> entrySet() {
885        EntrySet es = entrySet;
886        return (es != null) ? es : (entrySet = new EntrySet());
887    }
888
889    /**
890     * @since 1.6
891     */
892    public NavigableMap<K, V> descendingMap() {
893        NavigableMap<K, V> km = descendingMap;
894        return (km != null) ? km :
895            (descendingMap = new DescendingSubMap<>(this,
896                                                    true, null, true,
897                                                    true, null, true));
898    }
899
900    /**
901     * @throws ClassCastException       {@inheritDoc}
902     * @throws NullPointerException if {@code fromKey} or {@code toKey} is
903     *         null and this map uses natural ordering, or its comparator
904     *         does not permit null keys
905     * @throws IllegalArgumentException {@inheritDoc}
906     * @since 1.6
907     */
908    public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
909                                    K toKey,   boolean toInclusive) {
910        return new AscendingSubMap<>(this,
911                                     false, fromKey, fromInclusive,
912                                     false, toKey,   toInclusive);
913    }
914
915    /**
916     * @throws ClassCastException       {@inheritDoc}
917     * @throws NullPointerException if {@code toKey} is null
918     *         and this map uses natural ordering, or its comparator
919     *         does not permit null keys
920     * @throws IllegalArgumentException {@inheritDoc}
921     * @since 1.6
922     */
923    public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
924        return new AscendingSubMap<>(this,
925                                     true,  null,  true,
926                                     false, toKey, inclusive);
927    }
928
929    /**
930     * @throws ClassCastException       {@inheritDoc}
931     * @throws NullPointerException if {@code fromKey} is null
932     *         and this map uses natural ordering, or its comparator
933     *         does not permit null keys
934     * @throws IllegalArgumentException {@inheritDoc}
935     * @since 1.6
936     */
937    public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
938        return new AscendingSubMap<>(this,
939                                     false, fromKey, inclusive,
940                                     true,  null,    true);
941    }
942
943    /**
944     * @throws ClassCastException       {@inheritDoc}
945     * @throws NullPointerException if {@code fromKey} or {@code toKey} is
946     *         null and this map uses natural ordering, or its comparator
947     *         does not permit null keys
948     * @throws IllegalArgumentException {@inheritDoc}
949     */
950    public SortedMap<K,V> subMap(K fromKey, K toKey) {
951        return subMap(fromKey, true, toKey, false);
952    }
953
954    /**
955     * @throws ClassCastException       {@inheritDoc}
956     * @throws NullPointerException if {@code toKey} is null
957     *         and this map uses natural ordering, or its comparator
958     *         does not permit null keys
959     * @throws IllegalArgumentException {@inheritDoc}
960     */
961    public SortedMap<K,V> headMap(K toKey) {
962        return headMap(toKey, false);
963    }
964
965    /**
966     * @throws ClassCastException       {@inheritDoc}
967     * @throws NullPointerException if {@code fromKey} is null
968     *         and this map uses natural ordering, or its comparator
969     *         does not permit null keys
970     * @throws IllegalArgumentException {@inheritDoc}
971     */
972    public SortedMap<K,V> tailMap(K fromKey) {
973        return tailMap(fromKey, true);
974    }
975
976    @Override
977    public boolean replace(K key, V oldValue, V newValue) {
978        TreeMapEntry<K,V> p = getEntry(key);
979        if (p!=null && Objects.equals(oldValue, p.value)) {
980            p.value = newValue;
981            return true;
982        }
983        return false;
984    }
985
986    @Override
987    public V replace(K key, V value) {
988        TreeMapEntry<K,V> p = getEntry(key);
989        if (p!=null) {
990            V oldValue = p.value;
991            p.value = value;
992            return oldValue;
993        }
994        return null;
995    }
996
997    @Override
998    public void forEach(BiConsumer<? super K, ? super V> action) {
999        Objects.requireNonNull(action);
1000        int expectedModCount = modCount;
1001        for (TreeMapEntry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
1002            action.accept(e.key, e.value);
1003
1004            if (expectedModCount != modCount) {
1005                throw new ConcurrentModificationException();
1006            }
1007        }
1008    }
1009
1010    @Override
1011    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1012        Objects.requireNonNull(function);
1013        int expectedModCount = modCount;
1014
1015        for (TreeMapEntry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
1016            e.value = function.apply(e.key, e.value);
1017
1018            if (expectedModCount != modCount) {
1019                throw new ConcurrentModificationException();
1020            }
1021        }
1022    }
1023
1024    // View class support
1025
1026    class Values extends AbstractCollection<V> {
1027        public Iterator<V> iterator() {
1028            return new ValueIterator(getFirstEntry());
1029        }
1030
1031        public int size() {
1032            return TreeMap.this.size();
1033        }
1034
1035        public boolean contains(Object o) {
1036            return TreeMap.this.containsValue(o);
1037        }
1038
1039        public boolean remove(Object o) {
1040            for (TreeMapEntry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
1041                if (valEquals(e.getValue(), o)) {
1042                    deleteEntry(e);
1043                    return true;
1044                }
1045            }
1046            return false;
1047        }
1048
1049        public void clear() {
1050            TreeMap.this.clear();
1051        }
1052
1053        public Spliterator<V> spliterator() {
1054            return new ValueSpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
1055        }
1056    }
1057
1058    class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1059        public Iterator<Map.Entry<K,V>> iterator() {
1060            return new EntryIterator(getFirstEntry());
1061        }
1062
1063        public boolean contains(Object o) {
1064            if (!(o instanceof Map.Entry))
1065                return false;
1066            Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1067            V value = entry.getValue();
1068            TreeMapEntry<K,V> p = getEntry(entry.getKey());
1069            return p != null && valEquals(p.getValue(), value);
1070        }
1071
1072        public boolean remove(Object o) {
1073            if (!(o instanceof Map.Entry))
1074                return false;
1075            Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1076            V value = entry.getValue();
1077            TreeMapEntry<K,V> p = getEntry(entry.getKey());
1078            if (p != null && valEquals(p.getValue(), value)) {
1079                deleteEntry(p);
1080                return true;
1081            }
1082            return false;
1083        }
1084
1085        public int size() {
1086            return TreeMap.this.size();
1087        }
1088
1089        public void clear() {
1090            TreeMap.this.clear();
1091        }
1092
1093        public Spliterator<Map.Entry<K,V>> spliterator() {
1094            return new EntrySpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
1095        }
1096    }
1097
1098    /*
1099     * Unlike Values and EntrySet, the KeySet class is static,
1100     * delegating to a NavigableMap to allow use by SubMaps, which
1101     * outweighs the ugliness of needing type-tests for the following
1102     * Iterator methods that are defined appropriately in main versus
1103     * submap classes.
1104     */
1105
1106    Iterator<K> keyIterator() {
1107        return new KeyIterator(getFirstEntry());
1108    }
1109
1110    Iterator<K> descendingKeyIterator() {
1111        return new DescendingKeyIterator(getLastEntry());
1112    }
1113
1114    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
1115        private final NavigableMap<E, ?> m;
1116        KeySet(NavigableMap<E,?> map) { m = map; }
1117
1118        public Iterator<E> iterator() {
1119            if (m instanceof TreeMap)
1120                return ((TreeMap<E,?>)m).keyIterator();
1121            else
1122                return ((TreeMap.NavigableSubMap<E,?>)m).keyIterator();
1123        }
1124
1125        public Iterator<E> descendingIterator() {
1126            if (m instanceof TreeMap)
1127                return ((TreeMap<E,?>)m).descendingKeyIterator();
1128            else
1129                return ((TreeMap.NavigableSubMap<E,?>)m).descendingKeyIterator();
1130        }
1131
1132        public int size() { return m.size(); }
1133        public boolean isEmpty() { return m.isEmpty(); }
1134        public boolean contains(Object o) { return m.containsKey(o); }
1135        public void clear() { m.clear(); }
1136        public E lower(E e) { return m.lowerKey(e); }
1137        public E floor(E e) { return m.floorKey(e); }
1138        public E ceiling(E e) { return m.ceilingKey(e); }
1139        public E higher(E e) { return m.higherKey(e); }
1140        public E first() { return m.firstKey(); }
1141        public E last() { return m.lastKey(); }
1142        public Comparator<? super E> comparator() { return m.comparator(); }
1143        public E pollFirst() {
1144            Map.Entry<E,?> e = m.pollFirstEntry();
1145            return (e == null) ? null : e.getKey();
1146        }
1147        public E pollLast() {
1148            Map.Entry<E,?> e = m.pollLastEntry();
1149            return (e == null) ? null : e.getKey();
1150        }
1151        public boolean remove(Object o) {
1152            int oldSize = size();
1153            m.remove(o);
1154            return size() != oldSize;
1155        }
1156        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
1157                                      E toElement,   boolean toInclusive) {
1158            return new KeySet<>(m.subMap(fromElement, fromInclusive,
1159                                          toElement,   toInclusive));
1160        }
1161        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1162            return new KeySet<>(m.headMap(toElement, inclusive));
1163        }
1164        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1165            return new KeySet<>(m.tailMap(fromElement, inclusive));
1166        }
1167        public SortedSet<E> subSet(E fromElement, E toElement) {
1168            return subSet(fromElement, true, toElement, false);
1169        }
1170        public SortedSet<E> headSet(E toElement) {
1171            return headSet(toElement, false);
1172        }
1173        public SortedSet<E> tailSet(E fromElement) {
1174            return tailSet(fromElement, true);
1175        }
1176        public NavigableSet<E> descendingSet() {
1177            return new KeySet<>(m.descendingMap());
1178        }
1179
1180        public Spliterator<E> spliterator() {
1181            return keySpliteratorFor(m);
1182        }
1183    }
1184
1185    /**
1186     * Base class for TreeMap Iterators
1187     */
1188    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1189        TreeMapEntry<K,V> next;
1190        TreeMapEntry<K,V> lastReturned;
1191        int expectedModCount;
1192
1193        PrivateEntryIterator(TreeMapEntry<K,V> first) {
1194            expectedModCount = modCount;
1195            lastReturned = null;
1196            next = first;
1197        }
1198
1199        public final boolean hasNext() {
1200            return next != null;
1201        }
1202
1203        final TreeMapEntry<K,V> nextEntry() {
1204            TreeMapEntry<K,V> e = next;
1205            if (e == null)
1206                throw new NoSuchElementException();
1207            if (modCount != expectedModCount)
1208                throw new ConcurrentModificationException();
1209            next = successor(e);
1210            lastReturned = e;
1211            return e;
1212        }
1213
1214        final TreeMapEntry<K,V> prevEntry() {
1215            TreeMapEntry<K,V> e = next;
1216            if (e == null)
1217                throw new NoSuchElementException();
1218            if (modCount != expectedModCount)
1219                throw new ConcurrentModificationException();
1220            next = predecessor(e);
1221            lastReturned = e;
1222            return e;
1223        }
1224
1225        public void remove() {
1226            if (lastReturned == null)
1227                throw new IllegalStateException();
1228            if (modCount != expectedModCount)
1229                throw new ConcurrentModificationException();
1230            // deleted entries are replaced by their successors
1231            if (lastReturned.left != null && lastReturned.right != null)
1232                next = lastReturned;
1233            deleteEntry(lastReturned);
1234            expectedModCount = modCount;
1235            lastReturned = null;
1236        }
1237    }
1238
1239    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1240        EntryIterator(TreeMapEntry<K,V> first) {
1241            super(first);
1242        }
1243        public Map.Entry<K,V> next() {
1244            return nextEntry();
1245        }
1246    }
1247
1248    final class ValueIterator extends PrivateEntryIterator<V> {
1249        ValueIterator(TreeMapEntry<K,V> first) {
1250            super(first);
1251        }
1252        public V next() {
1253            return nextEntry().value;
1254        }
1255    }
1256
1257    final class KeyIterator extends PrivateEntryIterator<K> {
1258        KeyIterator(TreeMapEntry<K,V> first) {
1259            super(first);
1260        }
1261        public K next() {
1262            return nextEntry().key;
1263        }
1264    }
1265
1266    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1267        DescendingKeyIterator(TreeMapEntry<K,V> first) {
1268            super(first);
1269        }
1270        public K next() {
1271            return prevEntry().key;
1272        }
1273        public void remove() {
1274            if (lastReturned == null)
1275                throw new IllegalStateException();
1276            if (modCount != expectedModCount)
1277                throw new ConcurrentModificationException();
1278            deleteEntry(lastReturned);
1279            lastReturned = null;
1280            expectedModCount = modCount;
1281        }
1282    }
1283
1284    // Little utilities
1285
1286    /**
1287     * Compares two keys using the correct comparison method for this TreeMap.
1288     */
1289    @SuppressWarnings("unchecked")
1290    final int compare(Object k1, Object k2) {
1291        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1292            : comparator.compare((K)k1, (K)k2);
1293    }
1294
1295    /**
1296     * Test two values for equality.  Differs from o1.equals(o2) only in
1297     * that it copes with {@code null} o1 properly.
1298     */
1299    static final boolean valEquals(Object o1, Object o2) {
1300        return (o1==null ? o2==null : o1.equals(o2));
1301    }
1302
1303    /**
1304     * Return SimpleImmutableEntry for entry, or null if null
1305     */
1306    static <K,V> Map.Entry<K,V> exportEntry(TreeMapEntry<K,V> e) {
1307        return (e == null) ? null :
1308            new AbstractMap.SimpleImmutableEntry<>(e);
1309    }
1310
1311    /**
1312     * Return key for entry, or null if null
1313     */
1314    static <K,V> K keyOrNull(TreeMapEntry<K,V> e) {
1315        return (e == null) ? null : e.key;
1316    }
1317
1318    /**
1319     * Returns the key corresponding to the specified Entry.
1320     * @throws NoSuchElementException if the Entry is null
1321     */
1322    static <K> K key(TreeMapEntry<K,?> e) {
1323        if (e==null)
1324            throw new NoSuchElementException();
1325        return e.key;
1326    }
1327
1328
1329    // SubMaps
1330
1331    /**
1332     * Dummy value serving as unmatchable fence key for unbounded
1333     * SubMapIterators
1334     */
1335    private static final Object UNBOUNDED = new Object();
1336
1337    /**
1338     * @serial include
1339     */
1340    abstract static class NavigableSubMap<K,V> extends AbstractMap<K,V>
1341        implements NavigableMap<K,V>, java.io.Serializable {
1342        // Android-changed: Explicitly add a serialVersionUID so that we're serialization
1343        // compatible with the Java-7 version of this class. Several new methods were added
1344        // in Java-8 but none of them have any bearing on the serialized format of the class
1345        // or require any additional state to be preserved.
1346        private static final long serialVersionUID = 2765629423043303731L;
1347
1348        /**
1349         * The backing map.
1350         */
1351        final TreeMap<K,V> m;
1352
1353        /**
1354         * Endpoints are represented as triples (fromStart, lo,
1355         * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1356         * true, then the low (absolute) bound is the start of the
1357         * backing map, and the other values are ignored. Otherwise,
1358         * if loInclusive is true, lo is the inclusive bound, else lo
1359         * is the exclusive bound. Similarly for the upper bound.
1360         */
1361        final K lo, hi;
1362        final boolean fromStart, toEnd;
1363        final boolean loInclusive, hiInclusive;
1364
1365        NavigableSubMap(TreeMap<K,V> m,
1366                        boolean fromStart, K lo, boolean loInclusive,
1367                        boolean toEnd,     K hi, boolean hiInclusive) {
1368            if (!fromStart && !toEnd) {
1369                if (m.compare(lo, hi) > 0)
1370                    throw new IllegalArgumentException("fromKey > toKey");
1371            } else {
1372                if (!fromStart) // type check
1373                    m.compare(lo, lo);
1374                if (!toEnd)
1375                    m.compare(hi, hi);
1376            }
1377
1378            this.m = m;
1379            this.fromStart = fromStart;
1380            this.lo = lo;
1381            this.loInclusive = loInclusive;
1382            this.toEnd = toEnd;
1383            this.hi = hi;
1384            this.hiInclusive = hiInclusive;
1385        }
1386
1387        // internal utilities
1388
1389        final boolean tooLow(Object key) {
1390            if (!fromStart) {
1391                int c = m.compare(key, lo);
1392                if (c < 0 || (c == 0 && !loInclusive))
1393                    return true;
1394            }
1395            return false;
1396        }
1397
1398        final boolean tooHigh(Object key) {
1399            if (!toEnd) {
1400                int c = m.compare(key, hi);
1401                if (c > 0 || (c == 0 && !hiInclusive))
1402                    return true;
1403            }
1404            return false;
1405        }
1406
1407        final boolean inRange(Object key) {
1408            return !tooLow(key) && !tooHigh(key);
1409        }
1410
1411        final boolean inClosedRange(Object key) {
1412            return (fromStart || m.compare(key, lo) >= 0)
1413                && (toEnd || m.compare(hi, key) >= 0);
1414        }
1415
1416        final boolean inRange(Object key, boolean inclusive) {
1417            return inclusive ? inRange(key) : inClosedRange(key);
1418        }
1419
1420        /*
1421         * Absolute versions of relation operations.
1422         * Subclasses map to these using like-named "sub"
1423         * versions that invert senses for descending maps
1424         */
1425
1426        final TreeMapEntry<K,V> absLowest() {
1427            TreeMapEntry<K,V> e =
1428                (fromStart ?  m.getFirstEntry() :
1429                 (loInclusive ? m.getCeilingEntry(lo) :
1430                                m.getHigherEntry(lo)));
1431            return (e == null || tooHigh(e.key)) ? null : e;
1432        }
1433
1434        final TreeMapEntry<K,V> absHighest() {
1435            TreeMapEntry<K,V> e =
1436                (toEnd ?  m.getLastEntry() :
1437                 (hiInclusive ?  m.getFloorEntry(hi) :
1438                                 m.getLowerEntry(hi)));
1439            return (e == null || tooLow(e.key)) ? null : e;
1440        }
1441
1442        final TreeMapEntry<K,V> absCeiling(K key) {
1443            if (tooLow(key))
1444                return absLowest();
1445            TreeMapEntry<K,V> e = m.getCeilingEntry(key);
1446            return (e == null || tooHigh(e.key)) ? null : e;
1447        }
1448
1449        final TreeMapEntry<K,V> absHigher(K key) {
1450            if (tooLow(key))
1451                return absLowest();
1452            TreeMapEntry<K,V> e = m.getHigherEntry(key);
1453            return (e == null || tooHigh(e.key)) ? null : e;
1454        }
1455
1456        final TreeMapEntry<K,V> absFloor(K key) {
1457            if (tooHigh(key))
1458                return absHighest();
1459            TreeMapEntry<K,V> e = m.getFloorEntry(key);
1460            return (e == null || tooLow(e.key)) ? null : e;
1461        }
1462
1463        final TreeMapEntry<K,V> absLower(K key) {
1464            if (tooHigh(key))
1465                return absHighest();
1466            TreeMapEntry<K,V> e = m.getLowerEntry(key);
1467            return (e == null || tooLow(e.key)) ? null : e;
1468        }
1469
1470        /** Returns the absolute high fence for ascending traversal */
1471        final TreeMapEntry<K,V> absHighFence() {
1472            return (toEnd ? null : (hiInclusive ?
1473                                    m.getHigherEntry(hi) :
1474                                    m.getCeilingEntry(hi)));
1475        }
1476
1477        /** Return the absolute low fence for descending traversal  */
1478        final TreeMapEntry<K,V> absLowFence() {
1479            return (fromStart ? null : (loInclusive ?
1480                                        m.getLowerEntry(lo) :
1481                                        m.getFloorEntry(lo)));
1482        }
1483
1484        // Abstract methods defined in ascending vs descending classes
1485        // These relay to the appropriate absolute versions
1486
1487        abstract TreeMapEntry<K,V> subLowest();
1488        abstract TreeMapEntry<K,V> subHighest();
1489        abstract TreeMapEntry<K,V> subCeiling(K key);
1490        abstract TreeMapEntry<K,V> subHigher(K key);
1491        abstract TreeMapEntry<K,V> subFloor(K key);
1492        abstract TreeMapEntry<K,V> subLower(K key);
1493
1494        /** Returns ascending iterator from the perspective of this submap */
1495        abstract Iterator<K> keyIterator();
1496
1497        abstract Spliterator<K> keySpliterator();
1498
1499        /** Returns descending iterator from the perspective of this submap */
1500        abstract Iterator<K> descendingKeyIterator();
1501
1502        // public methods
1503
1504        public boolean isEmpty() {
1505            return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1506        }
1507
1508        public int size() {
1509            return (fromStart && toEnd) ? m.size() : entrySet().size();
1510        }
1511
1512        public final boolean containsKey(Object key) {
1513            return inRange(key) && m.containsKey(key);
1514        }
1515
1516        public final V put(K key, V value) {
1517            if (!inRange(key))
1518                throw new IllegalArgumentException("key out of range");
1519            return m.put(key, value);
1520        }
1521
1522        public final V get(Object key) {
1523            return !inRange(key) ? null :  m.get(key);
1524        }
1525
1526        public final V remove(Object key) {
1527            return !inRange(key) ? null : m.remove(key);
1528        }
1529
1530        public final Map.Entry<K,V> ceilingEntry(K key) {
1531            return exportEntry(subCeiling(key));
1532        }
1533
1534        public final K ceilingKey(K key) {
1535            return keyOrNull(subCeiling(key));
1536        }
1537
1538        public final Map.Entry<K,V> higherEntry(K key) {
1539            return exportEntry(subHigher(key));
1540        }
1541
1542        public final K higherKey(K key) {
1543            return keyOrNull(subHigher(key));
1544        }
1545
1546        public final Map.Entry<K,V> floorEntry(K key) {
1547            return exportEntry(subFloor(key));
1548        }
1549
1550        public final K floorKey(K key) {
1551            return keyOrNull(subFloor(key));
1552        }
1553
1554        public final Map.Entry<K,V> lowerEntry(K key) {
1555            return exportEntry(subLower(key));
1556        }
1557
1558        public final K lowerKey(K key) {
1559            return keyOrNull(subLower(key));
1560        }
1561
1562        public final K firstKey() {
1563            return key(subLowest());
1564        }
1565
1566        public final K lastKey() {
1567            return key(subHighest());
1568        }
1569
1570        public final Map.Entry<K,V> firstEntry() {
1571            return exportEntry(subLowest());
1572        }
1573
1574        public final Map.Entry<K,V> lastEntry() {
1575            return exportEntry(subHighest());
1576        }
1577
1578        public final Map.Entry<K,V> pollFirstEntry() {
1579            TreeMapEntry<K,V> e = subLowest();
1580            Map.Entry<K,V> result = exportEntry(e);
1581            if (e != null)
1582                m.deleteEntry(e);
1583            return result;
1584        }
1585
1586        public final Map.Entry<K,V> pollLastEntry() {
1587            TreeMapEntry<K,V> e = subHighest();
1588            Map.Entry<K,V> result = exportEntry(e);
1589            if (e != null)
1590                m.deleteEntry(e);
1591            return result;
1592        }
1593
1594        // Views
1595        transient NavigableMap<K,V> descendingMapView = null;
1596        transient EntrySetView entrySetView = null;
1597        transient KeySet<K> navigableKeySetView = null;
1598
1599        public final NavigableSet<K> navigableKeySet() {
1600            KeySet<K> nksv = navigableKeySetView;
1601            return (nksv != null) ? nksv :
1602                (navigableKeySetView = new TreeMap.KeySet<>(this));
1603        }
1604
1605        public final Set<K> keySet() {
1606            return navigableKeySet();
1607        }
1608
1609        public NavigableSet<K> descendingKeySet() {
1610            return descendingMap().navigableKeySet();
1611        }
1612
1613        public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1614            return subMap(fromKey, true, toKey, false);
1615        }
1616
1617        public final SortedMap<K,V> headMap(K toKey) {
1618            return headMap(toKey, false);
1619        }
1620
1621        public final SortedMap<K,V> tailMap(K fromKey) {
1622            return tailMap(fromKey, true);
1623        }
1624
1625        // View classes
1626
1627        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1628            private transient int size = -1, sizeModCount;
1629
1630            public int size() {
1631                if (fromStart && toEnd)
1632                    return m.size();
1633                if (size == -1 || sizeModCount != m.modCount) {
1634                    sizeModCount = m.modCount;
1635                    size = 0;
1636                    Iterator<?> i = iterator();
1637                    while (i.hasNext()) {
1638                        size++;
1639                        i.next();
1640                    }
1641                }
1642                return size;
1643            }
1644
1645            public boolean isEmpty() {
1646                TreeMapEntry<K,V> n = absLowest();
1647                return n == null || tooHigh(n.key);
1648            }
1649
1650            public boolean contains(Object o) {
1651                if (!(o instanceof Map.Entry))
1652                    return false;
1653                Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
1654                Object key = entry.getKey();
1655                if (!inRange(key))
1656                    return false;
1657                TreeMapEntry<?, ?> node = m.getEntry(key);
1658                return node != null &&
1659                    valEquals(node.getValue(), entry.getValue());
1660            }
1661
1662            public boolean remove(Object o) {
1663                if (!(o instanceof Map.Entry))
1664                    return false;
1665                Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
1666                Object key = entry.getKey();
1667                if (!inRange(key))
1668                    return false;
1669                TreeMapEntry<K,V> node = m.getEntry(key);
1670                if (node!=null && valEquals(node.getValue(),
1671                                            entry.getValue())) {
1672                    m.deleteEntry(node);
1673                    return true;
1674                }
1675                return false;
1676            }
1677        }
1678
1679        /**
1680         * Iterators for SubMaps
1681         */
1682        abstract class SubMapIterator<T> implements Iterator<T> {
1683            TreeMapEntry<K,V> lastReturned;
1684            TreeMapEntry<K,V> next;
1685            final Object fenceKey;
1686            int expectedModCount;
1687
1688            SubMapIterator(TreeMapEntry<K,V> first,
1689                           TreeMapEntry<K,V> fence) {
1690                expectedModCount = m.modCount;
1691                lastReturned = null;
1692                next = first;
1693                fenceKey = fence == null ? UNBOUNDED : fence.key;
1694            }
1695
1696            public final boolean hasNext() {
1697                return next != null && next.key != fenceKey;
1698            }
1699
1700            final TreeMapEntry<K,V> nextEntry() {
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 = successor(e);
1707                lastReturned = e;
1708                return e;
1709            }
1710
1711            final TreeMapEntry<K,V> prevEntry() {
1712                TreeMapEntry<K,V> e = next;
1713                if (e == null || e.key == fenceKey)
1714                    throw new NoSuchElementException();
1715                if (m.modCount != expectedModCount)
1716                    throw new ConcurrentModificationException();
1717                next = predecessor(e);
1718                lastReturned = e;
1719                return e;
1720            }
1721
1722            final void removeAscending() {
1723                if (lastReturned == null)
1724                    throw new IllegalStateException();
1725                if (m.modCount != expectedModCount)
1726                    throw new ConcurrentModificationException();
1727                // deleted entries are replaced by their successors
1728                if (lastReturned.left != null && lastReturned.right != null)
1729                    next = lastReturned;
1730                m.deleteEntry(lastReturned);
1731                lastReturned = null;
1732                expectedModCount = m.modCount;
1733            }
1734
1735            final void removeDescending() {
1736                if (lastReturned == null)
1737                    throw new IllegalStateException();
1738                if (m.modCount != expectedModCount)
1739                    throw new ConcurrentModificationException();
1740                m.deleteEntry(lastReturned);
1741                lastReturned = null;
1742                expectedModCount = m.modCount;
1743            }
1744
1745        }
1746
1747        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1748            SubMapEntryIterator(TreeMapEntry<K,V> first,
1749                                TreeMapEntry<K,V> fence) {
1750                super(first, fence);
1751            }
1752            public Map.Entry<K,V> next() {
1753                return nextEntry();
1754            }
1755            public void remove() {
1756                removeAscending();
1757            }
1758        }
1759
1760        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1761            DescendingSubMapEntryIterator(TreeMapEntry<K,V> last,
1762                                          TreeMapEntry<K,V> fence) {
1763                super(last, fence);
1764            }
1765
1766            public Map.Entry<K,V> next() {
1767                return prevEntry();
1768            }
1769            public void remove() {
1770                removeDescending();
1771            }
1772        }
1773
1774        // Implement minimal Spliterator as KeySpliterator backup
1775        final class SubMapKeyIterator extends SubMapIterator<K>
1776            implements Spliterator<K> {
1777            SubMapKeyIterator(TreeMapEntry<K,V> first,
1778                              TreeMapEntry<K,V> fence) {
1779                super(first, fence);
1780            }
1781            public K next() {
1782                return nextEntry().key;
1783            }
1784            public void remove() {
1785                removeAscending();
1786            }
1787            public Spliterator<K> trySplit() {
1788                return null;
1789            }
1790            public void forEachRemaining(Consumer<? super K> action) {
1791                while (hasNext())
1792                    action.accept(next());
1793            }
1794            public boolean tryAdvance(Consumer<? super K> action) {
1795                if (hasNext()) {
1796                    action.accept(next());
1797                    return true;
1798                }
1799                return false;
1800            }
1801            public long estimateSize() {
1802                return Long.MAX_VALUE;
1803            }
1804            public int characteristics() {
1805                return Spliterator.DISTINCT | Spliterator.ORDERED |
1806                    Spliterator.SORTED;
1807            }
1808            public final Comparator<? super K>  getComparator() {
1809                return NavigableSubMap.this.comparator();
1810            }
1811        }
1812
1813        final class DescendingSubMapKeyIterator extends SubMapIterator<K>
1814            implements Spliterator<K> {
1815            DescendingSubMapKeyIterator(TreeMapEntry<K,V> last,
1816                                        TreeMapEntry<K,V> fence) {
1817                super(last, fence);
1818            }
1819            public K next() {
1820                return prevEntry().key;
1821            }
1822            public void remove() {
1823                removeDescending();
1824            }
1825            public Spliterator<K> trySplit() {
1826                return null;
1827            }
1828            public void forEachRemaining(Consumer<? super K> action) {
1829                while (hasNext())
1830                    action.accept(next());
1831            }
1832            public boolean tryAdvance(Consumer<? super K> action) {
1833                if (hasNext()) {
1834                    action.accept(next());
1835                    return true;
1836                }
1837                return false;
1838            }
1839            public long estimateSize() {
1840                return Long.MAX_VALUE;
1841            }
1842            public int characteristics() {
1843                return Spliterator.DISTINCT | Spliterator.ORDERED;
1844            }
1845        }
1846    }
1847
1848    /**
1849     * @serial include
1850     */
1851    static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1852        private static final long serialVersionUID = 912986545866124060L;
1853
1854        AscendingSubMap(TreeMap<K,V> m,
1855                        boolean fromStart, K lo, boolean loInclusive,
1856                        boolean toEnd,     K hi, boolean hiInclusive) {
1857            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1858        }
1859
1860        public Comparator<? super K> comparator() {
1861            return m.comparator();
1862        }
1863
1864        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1865                                        K toKey,   boolean toInclusive) {
1866            if (!inRange(fromKey, fromInclusive))
1867                throw new IllegalArgumentException("fromKey out of range");
1868            if (!inRange(toKey, toInclusive))
1869                throw new IllegalArgumentException("toKey out of range");
1870            return new AscendingSubMap<>(m,
1871                                         false, fromKey, fromInclusive,
1872                                         false, toKey,   toInclusive);
1873        }
1874
1875        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1876            /* ----- BEGIN android -----
1877               Fix for edge cases
1878               if (!inRange(toKey, inclusive)) */
1879            if (!inRange(toKey) && !(!toEnd && m.compare(toKey, hi) == 0 &&
1880                !hiInclusive && !inclusive))
1881            // ----- END android -----
1882                throw new IllegalArgumentException("toKey out of range");
1883            return new AscendingSubMap<>(m,
1884                                         fromStart, lo,    loInclusive,
1885                                         false,     toKey, inclusive);
1886        }
1887
1888        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
1889            /* ----- BEGIN android -----
1890               Fix for edge cases
1891               if (!inRange(fromKey, inclusive)) */
1892            if (!inRange(fromKey) && !(!fromStart && m.compare(fromKey, lo) == 0 &&
1893                !loInclusive && !inclusive))
1894            // ----- END android -----
1895                throw new IllegalArgumentException("fromKey out of range");
1896            return new AscendingSubMap<>(m,
1897                                         false, fromKey, inclusive,
1898                                         toEnd, hi,      hiInclusive);
1899        }
1900
1901        public NavigableMap<K,V> descendingMap() {
1902            NavigableMap<K,V> mv = descendingMapView;
1903            return (mv != null) ? mv :
1904                (descendingMapView =
1905                 new DescendingSubMap<>(m,
1906                                        fromStart, lo, loInclusive,
1907                                        toEnd,     hi, hiInclusive));
1908        }
1909
1910        Iterator<K> keyIterator() {
1911            return new SubMapKeyIterator(absLowest(), absHighFence());
1912        }
1913
1914        Spliterator<K> keySpliterator() {
1915            return new SubMapKeyIterator(absLowest(), absHighFence());
1916        }
1917
1918        Iterator<K> descendingKeyIterator() {
1919            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1920        }
1921
1922        final class AscendingEntrySetView extends EntrySetView {
1923            public Iterator<Map.Entry<K,V>> iterator() {
1924                return new SubMapEntryIterator(absLowest(), absHighFence());
1925            }
1926        }
1927
1928        public Set<Map.Entry<K,V>> entrySet() {
1929            EntrySetView es = entrySetView;
1930            return (es != null) ? es : new AscendingEntrySetView();
1931        }
1932
1933        TreeMapEntry<K,V> subLowest()       { return absLowest(); }
1934        TreeMapEntry<K,V> subHighest()      { return absHighest(); }
1935        TreeMapEntry<K,V> subCeiling(K key) { return absCeiling(key); }
1936        TreeMapEntry<K,V> subHigher(K key)  { return absHigher(key); }
1937        TreeMapEntry<K,V> subFloor(K key)   { return absFloor(key); }
1938        TreeMapEntry<K,V> subLower(K key)   { return absLower(key); }
1939    }
1940
1941    /**
1942     * @serial include
1943     */
1944    static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1945        private static final long serialVersionUID = 912986545866120460L;
1946        DescendingSubMap(TreeMap<K,V> m,
1947                        boolean fromStart, K lo, boolean loInclusive,
1948                        boolean toEnd,     K hi, boolean hiInclusive) {
1949            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1950        }
1951
1952        private final Comparator<? super K> reverseComparator =
1953            Collections.reverseOrder(m.comparator);
1954
1955        public Comparator<? super K> comparator() {
1956            return reverseComparator;
1957        }
1958
1959        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1960                                        K toKey,   boolean toInclusive) {
1961            if (!inRange(fromKey, fromInclusive))
1962                throw new IllegalArgumentException("fromKey out of range");
1963            if (!inRange(toKey, toInclusive))
1964                throw new IllegalArgumentException("toKey out of range");
1965            return new DescendingSubMap<>(m,
1966                                          false, toKey,   toInclusive,
1967                                          false, fromKey, fromInclusive);
1968        }
1969
1970        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1971            /* ----- BEGIN android -----
1972               Fix for edge cases
1973               if (!inRange(toKey, inclusive)) */
1974            if (!inRange(toKey) && !(!fromStart && m.compare(toKey, lo) == 0 &&
1975                !loInclusive && !inclusive))
1976            // ----- END android -----
1977                throw new IllegalArgumentException("toKey out of range");
1978            return new DescendingSubMap<>(m,
1979                                          false, toKey, inclusive,
1980                                          toEnd, hi,    hiInclusive);
1981        }
1982
1983        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
1984            /* ----- BEGIN android -----
1985               Fix for edge cases
1986               if (!inRange(fromKey, inclusive)) */
1987            if (!inRange(fromKey) && !(!toEnd && m.compare(fromKey, hi) == 0 &&
1988                !hiInclusive && !inclusive))
1989            // ----- END android -----
1990                throw new IllegalArgumentException("fromKey out of range");
1991            return new DescendingSubMap<>(m,
1992                                          fromStart, lo, loInclusive,
1993                                          false, fromKey, inclusive);
1994        }
1995
1996        public NavigableMap<K,V> descendingMap() {
1997            NavigableMap<K,V> mv = descendingMapView;
1998            return (mv != null) ? mv :
1999                (descendingMapView =
2000                 new AscendingSubMap<>(m,
2001                                       fromStart, lo, loInclusive,
2002                                       toEnd,     hi, hiInclusive));
2003        }
2004
2005        Iterator<K> keyIterator() {
2006            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
2007        }
2008
2009        Spliterator<K> keySpliterator() {
2010            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
2011        }
2012
2013        Iterator<K> descendingKeyIterator() {
2014            return new SubMapKeyIterator(absLowest(), absHighFence());
2015        }
2016
2017        final class DescendingEntrySetView extends EntrySetView {
2018            public Iterator<Map.Entry<K,V>> iterator() {
2019                return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
2020            }
2021        }
2022
2023        public Set<Map.Entry<K,V>> entrySet() {
2024            EntrySetView es = entrySetView;
2025            return (es != null) ? es : (entrySetView = new DescendingEntrySetView());
2026        }
2027
2028        TreeMapEntry<K,V> subLowest()       { return absHighest(); }
2029        TreeMapEntry<K,V> subHighest()      { return absLowest(); }
2030        TreeMapEntry<K,V> subCeiling(K key) { return absFloor(key); }
2031        TreeMapEntry<K,V> subHigher(K key)  { return absLower(key); }
2032        TreeMapEntry<K,V> subFloor(K key)   { return absCeiling(key); }
2033        TreeMapEntry<K,V> subLower(K key)   { return absHigher(key); }
2034    }
2035
2036    /**
2037     * This class exists solely for the sake of serialization
2038     * compatibility with previous releases of TreeMap that did not
2039     * support NavigableMap.  It translates an old-version SubMap into
2040     * a new-version AscendingSubMap. This class is never otherwise
2041     * used.
2042     *
2043     * @serial include
2044     */
2045    private class SubMap extends AbstractMap<K,V>
2046        implements SortedMap<K,V>, java.io.Serializable {
2047        private static final long serialVersionUID = -6520786458950516097L;
2048        private boolean fromStart = false, toEnd = false;
2049        private K fromKey, toKey;
2050        private Object readResolve() {
2051            return new AscendingSubMap<>(TreeMap.this,
2052                                         fromStart, fromKey, true,
2053                                         toEnd, toKey, false);
2054        }
2055        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
2056        public K lastKey() { throw new InternalError(); }
2057        public K firstKey() { throw new InternalError(); }
2058        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
2059        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
2060        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
2061        public Comparator<? super K> comparator() { throw new InternalError(); }
2062    }
2063
2064
2065    // Red-black mechanics
2066
2067    private static final boolean RED   = false;
2068    private static final boolean BLACK = true;
2069
2070    /**
2071     * Node in the Tree.  Doubles as a means to pass key-value pairs back to
2072     * user (see Map.Entry).
2073     */
2074
2075    static final class TreeMapEntry<K,V> implements Map.Entry<K,V> {
2076        K key;
2077        V value;
2078        TreeMapEntry<K,V> left = null;
2079        TreeMapEntry<K,V> right = null;
2080        TreeMapEntry<K,V> parent;
2081        boolean color = BLACK;
2082
2083        /**
2084         * Make a new cell with given key, value, and parent, and with
2085         * {@code null} child links, and BLACK color.
2086         */
2087        TreeMapEntry(K key, V value, TreeMapEntry<K,V> parent) {
2088            this.key = key;
2089            this.value = value;
2090            this.parent = parent;
2091        }
2092
2093        /**
2094         * Returns the key.
2095         *
2096         * @return the key
2097         */
2098        public K getKey() {
2099            return key;
2100        }
2101
2102        /**
2103         * Returns the value associated with the key.
2104         *
2105         * @return the value associated with the key
2106         */
2107        public V getValue() {
2108            return value;
2109        }
2110
2111        /**
2112         * Replaces the value currently associated with the key with the given
2113         * value.
2114         *
2115         * @return the value associated with the key before this method was
2116         *         called
2117         */
2118        public V setValue(V value) {
2119            V oldValue = this.value;
2120            this.value = value;
2121            return oldValue;
2122        }
2123
2124        public boolean equals(Object o) {
2125            if (!(o instanceof Map.Entry))
2126                return false;
2127            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2128
2129            return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
2130        }
2131
2132        public int hashCode() {
2133            int keyHash = (key==null ? 0 : key.hashCode());
2134            int valueHash = (value==null ? 0 : value.hashCode());
2135            return keyHash ^ valueHash;
2136        }
2137
2138        public String toString() {
2139            return key + "=" + value;
2140        }
2141    }
2142
2143    /**
2144     * Returns the first Entry in the TreeMap (according to the TreeMap's
2145     * key-sort function).  Returns null if the TreeMap is empty.
2146     */
2147    final TreeMapEntry<K,V> getFirstEntry() {
2148        TreeMapEntry<K,V> p = root;
2149        if (p != null)
2150            while (p.left != null)
2151                p = p.left;
2152        return p;
2153    }
2154
2155    /**
2156     * Returns the last Entry in the TreeMap (according to the TreeMap's
2157     * key-sort function).  Returns null if the TreeMap is empty.
2158     */
2159    final TreeMapEntry<K,V> getLastEntry() {
2160        TreeMapEntry<K,V> p = root;
2161        if (p != null)
2162            while (p.right != null)
2163                p = p.right;
2164        return p;
2165    }
2166
2167    /**
2168     * Returns the successor of the specified Entry, or null if no such.
2169     */
2170    static <K,V> TreeMapEntry<K,V> successor(TreeMapEntry<K,V> t) {
2171        if (t == null)
2172            return null;
2173        else if (t.right != null) {
2174            TreeMapEntry<K,V> p = t.right;
2175            while (p.left != null)
2176                p = p.left;
2177            return p;
2178        } else {
2179            TreeMapEntry<K,V> p = t.parent;
2180            TreeMapEntry<K,V> ch = t;
2181            while (p != null && ch == p.right) {
2182                ch = p;
2183                p = p.parent;
2184            }
2185            return p;
2186        }
2187    }
2188
2189    /**
2190     * Returns the predecessor of the specified Entry, or null if no such.
2191     */
2192    static <K,V> TreeMapEntry<K,V> predecessor(TreeMapEntry<K,V> t) {
2193        if (t == null)
2194            return null;
2195        else if (t.left != null) {
2196            TreeMapEntry<K,V> p = t.left;
2197            while (p.right != null)
2198                p = p.right;
2199            return p;
2200        } else {
2201            TreeMapEntry<K,V> p = t.parent;
2202            TreeMapEntry<K,V> ch = t;
2203            while (p != null && ch == p.left) {
2204                ch = p;
2205                p = p.parent;
2206            }
2207            return p;
2208        }
2209    }
2210
2211    /**
2212     * Balancing operations.
2213     *
2214     * Implementations of rebalancings during insertion and deletion are
2215     * slightly different than the CLR version.  Rather than using dummy
2216     * nilnodes, we use a set of accessors that deal properly with null.  They
2217     * are used to avoid messiness surrounding nullness checks in the main
2218     * algorithms.
2219     */
2220
2221    private static <K,V> boolean colorOf(TreeMapEntry<K,V> p) {
2222        return (p == null ? BLACK : p.color);
2223    }
2224
2225    private static <K,V> TreeMapEntry<K,V> parentOf(TreeMapEntry<K,V> p) {
2226        return (p == null ? null: p.parent);
2227    }
2228
2229    private static <K,V> void setColor(TreeMapEntry<K,V> p, boolean c) {
2230        if (p != null)
2231            p.color = c;
2232    }
2233
2234    private static <K,V> TreeMapEntry<K,V> leftOf(TreeMapEntry<K,V> p) {
2235        return (p == null) ? null: p.left;
2236    }
2237
2238    private static <K,V> TreeMapEntry<K,V> rightOf(TreeMapEntry<K,V> p) {
2239        return (p == null) ? null: p.right;
2240    }
2241
2242    /** From CLR */
2243    private void rotateLeft(TreeMapEntry<K,V> p) {
2244        if (p != null) {
2245            TreeMapEntry<K,V> r = p.right;
2246            p.right = r.left;
2247            if (r.left != null)
2248                r.left.parent = p;
2249            r.parent = p.parent;
2250            if (p.parent == null)
2251                root = r;
2252            else if (p.parent.left == p)
2253                p.parent.left = r;
2254            else
2255                p.parent.right = r;
2256            r.left = p;
2257            p.parent = r;
2258        }
2259    }
2260
2261    /** From CLR */
2262    private void rotateRight(TreeMapEntry<K,V> p) {
2263        if (p != null) {
2264            TreeMapEntry<K,V> l = p.left;
2265            p.left = l.right;
2266            if (l.right != null) l.right.parent = p;
2267            l.parent = p.parent;
2268            if (p.parent == null)
2269                root = l;
2270            else if (p.parent.right == p)
2271                p.parent.right = l;
2272            else p.parent.left = l;
2273            l.right = p;
2274            p.parent = l;
2275        }
2276    }
2277
2278    /** From CLR */
2279    private void fixAfterInsertion(TreeMapEntry<K,V> x) {
2280        x.color = RED;
2281
2282        while (x != null && x != root && x.parent.color == RED) {
2283            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
2284                TreeMapEntry<K,V> y = rightOf(parentOf(parentOf(x)));
2285                if (colorOf(y) == RED) {
2286                    setColor(parentOf(x), BLACK);
2287                    setColor(y, BLACK);
2288                    setColor(parentOf(parentOf(x)), RED);
2289                    x = parentOf(parentOf(x));
2290                } else {
2291                    if (x == rightOf(parentOf(x))) {
2292                        x = parentOf(x);
2293                        rotateLeft(x);
2294                    }
2295                    setColor(parentOf(x), BLACK);
2296                    setColor(parentOf(parentOf(x)), RED);
2297                    rotateRight(parentOf(parentOf(x)));
2298                }
2299            } else {
2300                TreeMapEntry<K,V> y = leftOf(parentOf(parentOf(x)));
2301                if (colorOf(y) == RED) {
2302                    setColor(parentOf(x), BLACK);
2303                    setColor(y, BLACK);
2304                    setColor(parentOf(parentOf(x)), RED);
2305                    x = parentOf(parentOf(x));
2306                } else {
2307                    if (x == leftOf(parentOf(x))) {
2308                        x = parentOf(x);
2309                        rotateRight(x);
2310                    }
2311                    setColor(parentOf(x), BLACK);
2312                    setColor(parentOf(parentOf(x)), RED);
2313                    rotateLeft(parentOf(parentOf(x)));
2314                }
2315            }
2316        }
2317        root.color = BLACK;
2318    }
2319
2320    /**
2321     * Delete node p, and then rebalance the tree.
2322     */
2323    private void deleteEntry(TreeMapEntry<K,V> p) {
2324        modCount++;
2325        size--;
2326
2327        // If strictly internal, copy successor's element to p and then make p
2328        // point to successor.
2329        if (p.left != null && p.right != null) {
2330            TreeMapEntry<K,V> s = successor(p);
2331            p.key = s.key;
2332            p.value = s.value;
2333            p = s;
2334        } // p has 2 children
2335
2336        // Start fixup at replacement node, if it exists.
2337        TreeMapEntry<K,V> replacement = (p.left != null ? p.left : p.right);
2338
2339        if (replacement != null) {
2340            // Link replacement to parent
2341            replacement.parent = p.parent;
2342            if (p.parent == null)
2343                root = replacement;
2344            else if (p == p.parent.left)
2345                p.parent.left  = replacement;
2346            else
2347                p.parent.right = replacement;
2348
2349            // Null out links so they are OK to use by fixAfterDeletion.
2350            p.left = p.right = p.parent = null;
2351
2352            // Fix replacement
2353            if (p.color == BLACK)
2354                fixAfterDeletion(replacement);
2355        } else if (p.parent == null) { // return if we are the only node.
2356            root = null;
2357        } else { //  No children. Use self as phantom replacement and unlink.
2358            if (p.color == BLACK)
2359                fixAfterDeletion(p);
2360
2361            if (p.parent != null) {
2362                if (p == p.parent.left)
2363                    p.parent.left = null;
2364                else if (p == p.parent.right)
2365                    p.parent.right = null;
2366                p.parent = null;
2367            }
2368        }
2369    }
2370
2371    /** From CLR */
2372    private void fixAfterDeletion(TreeMapEntry<K,V> x) {
2373        while (x != root && colorOf(x) == BLACK) {
2374            if (x == leftOf(parentOf(x))) {
2375                TreeMapEntry<K,V> sib = rightOf(parentOf(x));
2376
2377                if (colorOf(sib) == RED) {
2378                    setColor(sib, BLACK);
2379                    setColor(parentOf(x), RED);
2380                    rotateLeft(parentOf(x));
2381                    sib = rightOf(parentOf(x));
2382                }
2383
2384                if (colorOf(leftOf(sib))  == BLACK &&
2385                    colorOf(rightOf(sib)) == BLACK) {
2386                    setColor(sib, RED);
2387                    x = parentOf(x);
2388                } else {
2389                    if (colorOf(rightOf(sib)) == BLACK) {
2390                        setColor(leftOf(sib), BLACK);
2391                        setColor(sib, RED);
2392                        rotateRight(sib);
2393                        sib = rightOf(parentOf(x));
2394                    }
2395                    setColor(sib, colorOf(parentOf(x)));
2396                    setColor(parentOf(x), BLACK);
2397                    setColor(rightOf(sib), BLACK);
2398                    rotateLeft(parentOf(x));
2399                    x = root;
2400                }
2401            } else { // symmetric
2402                TreeMapEntry<K,V> sib = leftOf(parentOf(x));
2403
2404                if (colorOf(sib) == RED) {
2405                    setColor(sib, BLACK);
2406                    setColor(parentOf(x), RED);
2407                    rotateRight(parentOf(x));
2408                    sib = leftOf(parentOf(x));
2409                }
2410
2411                if (colorOf(rightOf(sib)) == BLACK &&
2412                    colorOf(leftOf(sib)) == BLACK) {
2413                    setColor(sib, RED);
2414                    x = parentOf(x);
2415                } else {
2416                    if (colorOf(leftOf(sib)) == BLACK) {
2417                        setColor(rightOf(sib), BLACK);
2418                        setColor(sib, RED);
2419                        rotateLeft(sib);
2420                        sib = leftOf(parentOf(x));
2421                    }
2422                    setColor(sib, colorOf(parentOf(x)));
2423                    setColor(parentOf(x), BLACK);
2424                    setColor(leftOf(sib), BLACK);
2425                    rotateRight(parentOf(x));
2426                    x = root;
2427                }
2428            }
2429        }
2430
2431        setColor(x, BLACK);
2432    }
2433
2434    private static final long serialVersionUID = 919286545866124006L;
2435
2436    /**
2437     * Save the state of the {@code TreeMap} instance to a stream (i.e.,
2438     * serialize it).
2439     *
2440     * @serialData The <em>size</em> of the TreeMap (the number of key-value
2441     *             mappings) is emitted (int), followed by the key (Object)
2442     *             and value (Object) for each key-value mapping represented
2443     *             by the TreeMap. The key-value mappings are emitted in
2444     *             key-order (as determined by the TreeMap's Comparator,
2445     *             or by the keys' natural ordering if the TreeMap has no
2446     *             Comparator).
2447     */
2448    private void writeObject(java.io.ObjectOutputStream s)
2449        throws java.io.IOException {
2450        // Write out the Comparator and any hidden stuff
2451        s.defaultWriteObject();
2452
2453        // Write out size (number of Mappings)
2454        s.writeInt(size);
2455
2456        // Write out keys and values (alternating)
2457        for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
2458            Map.Entry<K,V> e = i.next();
2459            s.writeObject(e.getKey());
2460            s.writeObject(e.getValue());
2461        }
2462    }
2463
2464    /**
2465     * Reconstitute the {@code TreeMap} instance from a stream (i.e.,
2466     * deserialize it).
2467     */
2468    private void readObject(final java.io.ObjectInputStream s)
2469        throws java.io.IOException, ClassNotFoundException {
2470        // Read in the Comparator and any hidden stuff
2471        s.defaultReadObject();
2472
2473        // Read in size
2474        int size = s.readInt();
2475
2476        buildFromSorted(size, null, s, null);
2477    }
2478
2479    /** Intended to be called only from TreeSet.readObject */
2480    void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2481        throws java.io.IOException, ClassNotFoundException {
2482        buildFromSorted(size, null, s, defaultVal);
2483    }
2484
2485    /** Intended to be called only from TreeSet.addAll */
2486    void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2487        try {
2488            buildFromSorted(set.size(), set.iterator(), null, defaultVal);
2489        } catch (java.io.IOException cannotHappen) {
2490        } catch (ClassNotFoundException cannotHappen) {
2491        }
2492    }
2493
2494
2495    /**
2496     * Linear time tree building algorithm from sorted data.  Can accept keys
2497     * and/or values from iterator or stream. This leads to too many
2498     * parameters, but seems better than alternatives.  The four formats
2499     * that this method accepts are:
2500     *
2501     *    1) An iterator of Map.Entries.  (it != null, defaultVal == null).
2502     *    2) An iterator of keys.         (it != null, defaultVal != null).
2503     *    3) A stream of alternating serialized keys and values.
2504     *                                   (it == null, defaultVal == null).
2505     *    4) A stream of serialized keys. (it == null, defaultVal != null).
2506     *
2507     * It is assumed that the comparator of the TreeMap is already set prior
2508     * to calling this method.
2509     *
2510     * @param size the number of keys (or key-value pairs) to be read from
2511     *        the iterator or stream
2512     * @param it If non-null, new entries are created from entries
2513     *        or keys read from this iterator.
2514     * @param str If non-null, new entries are created from keys and
2515     *        possibly values read from this stream in serialized form.
2516     *        Exactly one of it and str should be non-null.
2517     * @param defaultVal if non-null, this default value is used for
2518     *        each value in the map.  If null, each value is read from
2519     *        iterator or stream, as described above.
2520     * @throws java.io.IOException propagated from stream reads. This cannot
2521     *         occur if str is null.
2522     * @throws ClassNotFoundException propagated from readObject.
2523     *         This cannot occur if str is null.
2524     */
2525    private void buildFromSorted(int size, Iterator<?> it,
2526                                 java.io.ObjectInputStream str,
2527                                 V defaultVal)
2528        throws  java.io.IOException, ClassNotFoundException {
2529        this.size = size;
2530        root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2531                               it, str, defaultVal);
2532    }
2533
2534    /**
2535     * Recursive "helper method" that does the real work of the
2536     * previous method.  Identically named parameters have
2537     * identical definitions.  Additional parameters are documented below.
2538     * It is assumed that the comparator and size fields of the TreeMap are
2539     * already set prior to calling this method.  (It ignores both fields.)
2540     *
2541     * @param level the current level of tree. Initial call should be 0.
2542     * @param lo the first element index of this subtree. Initial should be 0.
2543     * @param hi the last element index of this subtree.  Initial should be
2544     *        size-1.
2545     * @param redLevel the level at which nodes should be red.
2546     *        Must be equal to computeRedLevel for tree of this size.
2547     */
2548    @SuppressWarnings("unchecked")
2549    private final TreeMapEntry<K,V> buildFromSorted(int level, int lo, int hi,
2550                                             int redLevel,
2551                                             Iterator<?> it,
2552                                             java.io.ObjectInputStream str,
2553                                             V defaultVal)
2554        throws  java.io.IOException, ClassNotFoundException {
2555        /*
2556         * Strategy: The root is the middlemost element. To get to it, we
2557         * have to first recursively construct the entire left subtree,
2558         * so as to grab all of its elements. We can then proceed with right
2559         * subtree.
2560         *
2561         * The lo and hi arguments are the minimum and maximum
2562         * indices to pull out of the iterator or stream for current subtree.
2563         * They are not actually indexed, we just proceed sequentially,
2564         * ensuring that items are extracted in corresponding order.
2565         */
2566
2567        if (hi < lo) return null;
2568
2569        int mid = (lo + hi) >>> 1;
2570
2571        TreeMapEntry<K,V> left  = null;
2572        if (lo < mid)
2573            left = buildFromSorted(level+1, lo, mid - 1, redLevel,
2574                                   it, str, defaultVal);
2575
2576        // extract key and/or value from iterator or stream
2577        K key;
2578        V value;
2579        if (it != null) {
2580            if (defaultVal==null) {
2581                Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
2582                key = entry.getKey();
2583                value = entry.getValue();
2584            } else {
2585                key = (K)it.next();
2586                value = defaultVal;
2587            }
2588        } else { // use stream
2589            key = (K) str.readObject();
2590            value = (defaultVal != null ? defaultVal : (V) str.readObject());
2591        }
2592
2593        TreeMapEntry<K,V> middle =  new TreeMapEntry<>(key, value, null);
2594
2595        // color nodes in non-full bottommost level red
2596        if (level == redLevel)
2597            middle.color = RED;
2598
2599        if (left != null) {
2600            middle.left = left;
2601            left.parent = middle;
2602        }
2603
2604        if (mid < hi) {
2605            TreeMapEntry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
2606                                               it, str, defaultVal);
2607            middle.right = right;
2608            right.parent = middle;
2609        }
2610
2611        return middle;
2612    }
2613
2614    /**
2615     * Find the level down to which to assign all nodes BLACK.  This is the
2616     * last `full' level of the complete binary tree produced by
2617     * buildTree. The remaining nodes are colored RED. (This makes a `nice'
2618     * set of color assignments wrt future insertions.) This level number is
2619     * computed by finding the number of splits needed to reach the zeroeth
2620     * node.  (The answer is ~lg(N), but in any case must be computed by same
2621     * quick O(lg(N)) loop.)
2622     */
2623    private static int computeRedLevel(int sz) {
2624        int level = 0;
2625        for (int m = sz - 1; m >= 0; m = m / 2 - 1)
2626            level++;
2627        return level;
2628    }
2629
2630    /**
2631     * Currently, we support Spliterator-based versions only for the
2632     * full map, in either plain of descending form, otherwise relying
2633     * on defaults because size estimation for submaps would dominate
2634     * costs. The type tests needed to check these for key views are
2635     * not very nice but avoid disrupting existing class
2636     * structures. Callers must use plain default spliterators if this
2637     * returns null.
2638     */
2639    static <K> Spliterator<K> keySpliteratorFor(NavigableMap<K,?> m) {
2640        if (m instanceof TreeMap) {
2641            @SuppressWarnings("unchecked") TreeMap<K,Object> t =
2642                (TreeMap<K,Object>) m;
2643            return t.keySpliterator();
2644        }
2645        if (m instanceof DescendingSubMap) {
2646            @SuppressWarnings("unchecked") DescendingSubMap<K,?> dm =
2647                (DescendingSubMap<K,?>) m;
2648            TreeMap<K,?> tm = dm.m;
2649            if (dm == tm.descendingMap) {
2650                @SuppressWarnings("unchecked") TreeMap<K,Object> t =
2651                    (TreeMap<K,Object>) tm;
2652                return t.descendingKeySpliterator();
2653            }
2654        }
2655        @SuppressWarnings("unchecked") NavigableSubMap<K,?> sm =
2656            (NavigableSubMap<K,?>) m;
2657        return sm.keySpliterator();
2658    }
2659
2660    final Spliterator<K> keySpliterator() {
2661        return new KeySpliterator<K,V>(this, null, null, 0, -1, 0);
2662    }
2663
2664    final Spliterator<K> descendingKeySpliterator() {
2665        return new DescendingKeySpliterator<K,V>(this, null, null, 0, -2, 0);
2666    }
2667
2668    /**
2669     * Base class for spliterators.  Iteration starts at a given
2670     * origin and continues up to but not including a given fence (or
2671     * null for end).  At top-level, for ascending cases, the first
2672     * split uses the root as left-fence/right-origin. From there,
2673     * right-hand splits replace the current fence with its left
2674     * child, also serving as origin for the split-off spliterator.
2675     * Left-hands are symmetric. Descending versions place the origin
2676     * at the end and invert ascending split rules.  This base class
2677     * is non-commital about directionality, or whether the top-level
2678     * spliterator covers the whole tree. This means that the actual
2679     * split mechanics are located in subclasses. Some of the subclass
2680     * trySplit methods are identical (except for return types), but
2681     * not nicely factorable.
2682     *
2683     * Currently, subclass versions exist only for the full map
2684     * (including descending keys via its descendingMap).  Others are
2685     * possible but currently not worthwhile because submaps require
2686     * O(n) computations to determine size, which substantially limits
2687     * potential speed-ups of using custom Spliterators versus default
2688     * mechanics.
2689     *
2690     * To boostrap initialization, external constructors use
2691     * negative size estimates: -1 for ascend, -2 for descend.
2692     */
2693    static class TreeMapSpliterator<K,V> {
2694        final TreeMap<K,V> tree;
2695        TreeMapEntry<K,V> current; // traverser; initially first node in range
2696        TreeMapEntry<K,V> fence;   // one past last, or null
2697        int side;                   // 0: top, -1: is a left split, +1: right
2698        int est;                    // size estimate (exact only for top-level)
2699        int expectedModCount;       // for CME checks
2700
2701        TreeMapSpliterator(TreeMap<K,V> tree,
2702                           TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2703                           int side, int est, int expectedModCount) {
2704            this.tree = tree;
2705            this.current = origin;
2706            this.fence = fence;
2707            this.side = side;
2708            this.est = est;
2709            this.expectedModCount = expectedModCount;
2710        }
2711
2712        final int getEstimate() { // force initialization
2713            int s; TreeMap<K,V> t;
2714            if ((s = est) < 0) {
2715                if ((t = tree) != null) {
2716                    current = (s == -1) ? t.getFirstEntry() : t.getLastEntry();
2717                    s = est = t.size;
2718                    expectedModCount = t.modCount;
2719                }
2720                else
2721                    s = est = 0;
2722            }
2723            return s;
2724        }
2725
2726        public final long estimateSize() {
2727            return (long)getEstimate();
2728        }
2729    }
2730
2731    static final class KeySpliterator<K,V>
2732        extends TreeMapSpliterator<K,V>
2733        implements Spliterator<K> {
2734        KeySpliterator(TreeMap<K,V> tree,
2735                       TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2736                       int side, int est, int expectedModCount) {
2737            super(tree, origin, fence, side, est, expectedModCount);
2738        }
2739
2740        public KeySpliterator<K,V> trySplit() {
2741            if (est < 0)
2742                getEstimate(); // force initialization
2743            int d = side;
2744            TreeMapEntry<K,V> e = current, f = fence,
2745                s = ((e == null || e == f) ? null :      // empty
2746                     (d == 0)              ? tree.root : // was top
2747                     (d >  0)              ? e.right :   // was right
2748                     (d <  0 && f != null) ? f.left :    // was left
2749                     null);
2750            if (s != null && s != e && s != f &&
2751                tree.compare(e.key, s.key) < 0) {        // e not already past s
2752                side = 1;
2753                return new KeySpliterator<>
2754                    (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2755            }
2756            return null;
2757        }
2758
2759        public void forEachRemaining(Consumer<? super K> action) {
2760            if (action == null)
2761                throw new NullPointerException();
2762            if (est < 0)
2763                getEstimate(); // force initialization
2764            TreeMapEntry<K,V> f = fence, e, p, pl;
2765            if ((e = current) != null && e != f) {
2766                current = f; // exhaust
2767                do {
2768                    action.accept(e.key);
2769                    if ((p = e.right) != null) {
2770                        while ((pl = p.left) != null)
2771                            p = pl;
2772                    }
2773                    else {
2774                        while ((p = e.parent) != null && e == p.right)
2775                            e = p;
2776                    }
2777                } while ((e = p) != null && e != f);
2778                if (tree.modCount != expectedModCount)
2779                    throw new ConcurrentModificationException();
2780            }
2781        }
2782
2783        public boolean tryAdvance(Consumer<? super K> action) {
2784            TreeMapEntry<K,V> e;
2785            if (action == null)
2786                throw new NullPointerException();
2787            if (est < 0)
2788                getEstimate(); // force initialization
2789            if ((e = current) == null || e == fence)
2790                return false;
2791            current = successor(e);
2792            action.accept(e.key);
2793            if (tree.modCount != expectedModCount)
2794                throw new ConcurrentModificationException();
2795            return true;
2796        }
2797
2798        public int characteristics() {
2799            return (side == 0 ? Spliterator.SIZED : 0) |
2800                Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
2801        }
2802
2803        public final Comparator<? super K>  getComparator() {
2804            return tree.comparator;
2805        }
2806
2807    }
2808
2809    static final class DescendingKeySpliterator<K,V>
2810        extends TreeMapSpliterator<K,V>
2811        implements Spliterator<K> {
2812        DescendingKeySpliterator(TreeMap<K,V> tree,
2813                                 TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2814                                 int side, int est, int expectedModCount) {
2815            super(tree, origin, fence, side, est, expectedModCount);
2816        }
2817
2818        public DescendingKeySpliterator<K,V> trySplit() {
2819            if (est < 0)
2820                getEstimate(); // force initialization
2821            int d = side;
2822            TreeMapEntry<K,V> e = current, f = fence,
2823                    s = ((e == null || e == f) ? null :      // empty
2824                         (d == 0)              ? tree.root : // was top
2825                         (d <  0)              ? e.left :    // was left
2826                         (d >  0 && f != null) ? f.right :   // was right
2827                         null);
2828            if (s != null && s != e && s != f &&
2829                tree.compare(e.key, s.key) > 0) {       // e not already past s
2830                side = 1;
2831                return new DescendingKeySpliterator<>
2832                        (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2833            }
2834            return null;
2835        }
2836
2837        public void forEachRemaining(Consumer<? super K> action) {
2838            if (action == null)
2839                throw new NullPointerException();
2840            if (est < 0)
2841                getEstimate(); // force initialization
2842            TreeMapEntry<K,V> f = fence, e, p, pr;
2843            if ((e = current) != null && e != f) {
2844                current = f; // exhaust
2845                do {
2846                    action.accept(e.key);
2847                    if ((p = e.left) != null) {
2848                        while ((pr = p.right) != null)
2849                            p = pr;
2850                    }
2851                    else {
2852                        while ((p = e.parent) != null && e == p.left)
2853                            e = p;
2854                    }
2855                } while ((e = p) != null && e != f);
2856                if (tree.modCount != expectedModCount)
2857                    throw new ConcurrentModificationException();
2858            }
2859        }
2860
2861        public boolean tryAdvance(Consumer<? super K> action) {
2862            TreeMapEntry<K,V> e;
2863            if (action == null)
2864                throw new NullPointerException();
2865            if (est < 0)
2866                getEstimate(); // force initialization
2867            if ((e = current) == null || e == fence)
2868                return false;
2869            current = predecessor(e);
2870            action.accept(e.key);
2871            if (tree.modCount != expectedModCount)
2872                throw new ConcurrentModificationException();
2873            return true;
2874        }
2875
2876        public int characteristics() {
2877            return (side == 0 ? Spliterator.SIZED : 0) |
2878                Spliterator.DISTINCT | Spliterator.ORDERED;
2879        }
2880    }
2881
2882    static final class ValueSpliterator<K,V>
2883            extends TreeMapSpliterator<K,V>
2884            implements Spliterator<V> {
2885        ValueSpliterator(TreeMap<K,V> tree,
2886                         TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2887                         int side, int est, int expectedModCount) {
2888            super(tree, origin, fence, side, est, expectedModCount);
2889        }
2890
2891        public ValueSpliterator<K,V> trySplit() {
2892            if (est < 0)
2893                getEstimate(); // force initialization
2894            int d = side;
2895            TreeMapEntry<K,V> e = current, f = fence,
2896                    s = ((e == null || e == f) ? null :      // empty
2897                         (d == 0)              ? tree.root : // was top
2898                         (d >  0)              ? e.right :   // was right
2899                         (d <  0 && f != null) ? f.left :    // was left
2900                         null);
2901            if (s != null && s != e && s != f &&
2902                tree.compare(e.key, s.key) < 0) {        // e not already past s
2903                side = 1;
2904                return new ValueSpliterator<>
2905                        (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2906            }
2907            return null;
2908        }
2909
2910        public void forEachRemaining(Consumer<? super V> action) {
2911            if (action == null)
2912                throw new NullPointerException();
2913            if (est < 0)
2914                getEstimate(); // force initialization
2915            TreeMapEntry<K,V> f = fence, e, p, pl;
2916            if ((e = current) != null && e != f) {
2917                current = f; // exhaust
2918                do {
2919                    action.accept(e.value);
2920                    if ((p = e.right) != null) {
2921                        while ((pl = p.left) != null)
2922                            p = pl;
2923                    }
2924                    else {
2925                        while ((p = e.parent) != null && e == p.right)
2926                            e = p;
2927                    }
2928                } while ((e = p) != null && e != f);
2929                if (tree.modCount != expectedModCount)
2930                    throw new ConcurrentModificationException();
2931            }
2932        }
2933
2934        public boolean tryAdvance(Consumer<? super V> action) {
2935            TreeMapEntry<K,V> e;
2936            if (action == null)
2937                throw new NullPointerException();
2938            if (est < 0)
2939                getEstimate(); // force initialization
2940            if ((e = current) == null || e == fence)
2941                return false;
2942            current = successor(e);
2943            action.accept(e.value);
2944            if (tree.modCount != expectedModCount)
2945                throw new ConcurrentModificationException();
2946            return true;
2947        }
2948
2949        public int characteristics() {
2950            return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.ORDERED;
2951        }
2952    }
2953
2954    static final class EntrySpliterator<K,V>
2955        extends TreeMapSpliterator<K,V>
2956        implements Spliterator<Map.Entry<K,V>> {
2957        EntrySpliterator(TreeMap<K,V> tree,
2958                         TreeMapEntry<K,V> origin, TreeMapEntry<K,V> fence,
2959                         int side, int est, int expectedModCount) {
2960            super(tree, origin, fence, side, est, expectedModCount);
2961        }
2962
2963        public EntrySpliterator<K,V> trySplit() {
2964            if (est < 0)
2965                getEstimate(); // force initialization
2966            int d = side;
2967            TreeMapEntry<K,V> e = current, f = fence,
2968                    s = ((e == null || e == f) ? null :      // empty
2969                         (d == 0)              ? tree.root : // was top
2970                         (d >  0)              ? e.right :   // was right
2971                         (d <  0 && f != null) ? f.left :    // was left
2972                         null);
2973            if (s != null && s != e && s != f &&
2974                tree.compare(e.key, s.key) < 0) {        // e not already past s
2975                side = 1;
2976                return new EntrySpliterator<>
2977                        (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2978            }
2979            return null;
2980        }
2981
2982        public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
2983            if (action == null)
2984                throw new NullPointerException();
2985            if (est < 0)
2986                getEstimate(); // force initialization
2987            TreeMapEntry<K,V> f = fence, e, p, pl;
2988            if ((e = current) != null && e != f) {
2989                current = f; // exhaust
2990                do {
2991                    action.accept(e);
2992                    if ((p = e.right) != null) {
2993                        while ((pl = p.left) != null)
2994                            p = pl;
2995                    }
2996                    else {
2997                        while ((p = e.parent) != null && e == p.right)
2998                            e = p;
2999                    }
3000                } while ((e = p) != null && e != f);
3001                if (tree.modCount != expectedModCount)
3002                    throw new ConcurrentModificationException();
3003            }
3004        }
3005
3006        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3007            TreeMapEntry<K,V> e;
3008            if (action == null)
3009                throw new NullPointerException();
3010            if (est < 0)
3011                getEstimate(); // force initialization
3012            if ((e = current) == null || e == fence)
3013                return false;
3014            current = successor(e);
3015            action.accept(e);
3016            if (tree.modCount != expectedModCount)
3017                throw new ConcurrentModificationException();
3018            return true;
3019        }
3020
3021        public int characteristics() {
3022            return (side == 0 ? Spliterator.SIZED : 0) |
3023                    Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
3024        }
3025
3026        @Override
3027        public Comparator<Map.Entry<K, V>> getComparator() {
3028            // Adapt or create a key-based comparator
3029            if (tree.comparator != null) {
3030                return Map.Entry.comparingByKey(tree.comparator);
3031            }
3032            else {
3033                return (Comparator<Map.Entry<K, V>> & Serializable) (e1, e2) -> {
3034                    @SuppressWarnings("unchecked")
3035                    Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey();
3036                    return k1.compareTo(e2.getKey());
3037                };
3038            }
3039        }
3040    }
3041}
3042