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