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