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