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